Tell us what’s happening:
I haven’s put a g flag in text, yet it matches all characters of myRegex. I don’t understand that.
Your code so far
let text = "titanic";
let myRegex = /t[a-z]*i/; // Change this line
let result = text.match(myRegex);
Your browser information:
User Agent is:
Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36.
Link to the challenge:
Global matching /g means all matches, so without the /g flag it will return after first match.
A * is for all results of the previous character or expression.
So what your regex is doing is
t // match on character t
[a-z]* // match zero or more of characters a-z
i // up to and including character i
It isn’t matching everything, it matches on
"titani" (note, not the last “c”). The match is greedy, so it keeps going until it can’t match any more.
i // this is in group a-z
i // no more i characters after this, so match ends
The question mark there will stop it being greedy, so instead of matching
"titani", it will match
"ti" (there are zero characters between “t” and the first “i”), which is what I think you expected.
Even c is included in [a-z]
Why is it not included ?
You’re only saying match until you reach the [specific] character
But we find “i” character right at first match. Why didn’t it stop at first match as it itself is “i”
This is going around in circles a bit but:
You match a sequence of characters starting with t, then possibly some a-z, then ending in i
Does that mean that it will keep matching until last “I” that it finds in string. Or will it stop right at first “I” found ?
Right, this is really going round in circles:
Yes, it will keep.matching because it is greedy. To stop it being a greedy match, the
? is used.
Okk, I got that lol. Was just a bit confused. No more circles.
Thanks for helping and going in circle 3 times…