by @saigowthamr

How to count string occurrences in a string JavaScript

Home » javascript » How to count string occurrences in a string JavaScript

To count the string occurrences in a given string, we can use the match() method in JavaScript.

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

Best Web Development courses