Use a RegEx to count the number of “o” occurs in a string.
var str = 'www.codingrepo.com';
Let me explain how this works:
str.match() is a RegEx method. It searches for the specified RegEx inside the specified string (in this case, the string is “str“).
/o/gi) This is the actual RegEx. It reads, “find the character o” It’s very simple. It also carries two flags, the “
g” and the “
i“. The “
g” says to find ALL occurrences of the character “o”, otherwise it would only find the first one, and it would never count past the number one. The second flag is “
i“. It makes the RegEx match all cases of that character.