So the ^ indicates the start of the string, and the $ indicates the end of a string.
So you’d be matching something only containing those three repeating numbers, nothing more.
As far as matching 42 42 42 42, its just looking for 3 pairs of numbers in a row… but without the ^ and $ it doesn’t care whats before or after those three numers, so it will match and return an array with the first 3 42’s, and the last three 42’s… its wanting no match at all, thats why you need the start and end markers.
So the default behaviour is that it will keep going until it finds something that doesn’t match? And in the case you need it to keep going to the very end of the string regardless of no matches, you need to use the g flag.
Also, with the ^ and $ you’re specifying the start and end of the regex therefore making it match once what’s in the regex.
Is that right?
OK, you caught me there. Without the g, it will only find the first match. g tells it to repeat and find additional matches, not just the first.
but even without the g, 42 42 42 42 would still return a match, which is what they don’t want.
So the start and end tags indicate that your wanting something at the start or end of the string. For instance:
let myString = "This is my dog";
let regEx1 = /dog/;
let regEx2 = /dog$/;
let redEx3 = /^dog/;
let regEx4 = /^dog$/;
So regEx1 is looking for 'dog' with no regard to whats before or behind it, it would return a match in myString. regEx2 is saying to search for dog, then the end of string. It doesn’t care whats before it, but its wanting nothing behind it. It would also match to myString because it ends in dog. regEx3 would wouldn’t match… it wants a string that starts with dog. regEx4 also wouldn’t match because its looking for start of string, the word dog, then immediately end of string, meaning it would only match a string containing only the word dog, nothing else.
So without ^ and $ in your repeating number string example, it would return a match for all of these;
^...$ will make sure the string you match persists of exactly whats inside the regex, no additional text
const long = 'looking for a string that only includes freecodecamp';
const short = 'freecodecamp';
Notice how, when i wrap “freecodecamp” with ^-$, it returns false for strings that persist of more than what i am looking. I want to restrict my search to the exact regex
Thank you! I get it now, so it will return true because its finding the regex in the string (no matter where it is), and if you want it to match exactly what’s in the regex you can use ^ and $ since that would mean you want the string to have exactly what’s in the regex, i.e. it starts and finishes just as the regex pattern.