Regular Expressions: Match Characters that Occur Zero or More Times question

There is this code:

let soccerWord = "gooooooooal!";
let gPhrase = "gut feeling";
let oPhrase = "over the moon";
let goRegex = /go*/;
soccerWord.match(goRegex); // Returns ["goooooooo"]
gPhrase.match(goRegex); // Returns ["g"]
oPhrase.match(goRegex); // Returns null

Why oPhrase.match(goRegex); returns null and not the os?

You’re looking for a “g” followed by zero or more “o” characters. There is no “g” in “over the moon”, therefore the function returns null, no matches.

Here is a good tool to test out how your regex will respond.

I use it all the time as a sanity check.

Thanks for the replies.

DanCouper is that null in a array?

See documentation:

Thanks for the reply.

Hmm, this doesn’t seem clear to me from the instructions:

“There’s also an option that matches characters that occur zero or more times. The character to do this is the asterisk or star: * .”

Based on the above instructions, it would seem that we are matching either “g” or “o” to see if either one occurs zero or more times. So there is no “g” in over the moon, but there are many "o"s. So why does oPhrase.match(goRegex); return null?

It matches the preceding character zero or more times. So


Tries to find a g followed by zero or more os, so will match g, go, goo, gooo and so on.

Ok thanks, that’s not at all clear from the instructions.