Regular Expression: Count the Number of Occurences of a Character in a String

Use a RegEx to count the number of “o” occurs in a string.

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.

Leave a Reply

Your email address will not be published. Required fields are marked *

CAPTCHA