Helpful clarification for RegEx - Match Characters that Occur Zero or More Times

The “gooooal” example here took me quite awhile to understand. There are many good explanations on here, but I was confused for awhile about the flags and the example used in the explanation.

let soccerWord = "gooooooooal!";
let gPhrase = "gut feeling";
let oPhrase = "over the moon";
let goRegex = /go*/;
soccerWord.match(goRegex);
gPhrase.match(goRegex);
oPhrase.match(goRegex);

To test this out, I headed over to https://regexr.com/ and ran the following 3 tests:

At first, I couldn’t understand why the example didn’t use the g flag but still returned the ["g"] from gut feeling. In the first test in my image, not using a g flag results in the g from gut not being matched. Using the g flag in the second test, it does match the g from gut.

Finally I realized this was because the example provided here is using two distinct strings soccerWord and gPhrase but my tests were regarded as single strings which was why I had to include a g flag. In the last test I am able to get the same result as the example here by only putting the word “gut” in my string and not needing the g flag.

Hope this helps someone!

Challenge: Regular Expressions - Match Characters that Occur Zero or More Times

Link to the challenge:

Yeah, the g flag means global, meaning to return all match in the string. Without the g flag, the search only returns the first match it finds, but not any additional matches.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.