To count the string occurrences in a given string, we can use the
match() method accepts the regular expression as an argument and it returns the array of matched values.
Here is an example, that counts the character
ok in the following string.
const str = "he is ok, are you ok, hobby lol ok"; const count = str.match(/ok/g).length; console.log(count); // 3
In the example, we have passed the regular expression
/ok/g to the
match() method. so it returns the array of matched
ok values in the string.
g is the global flag in regular expression, we used above to find out the matched values all over the string.