w3docs logo
  1. Snippets
  2. JavaScript
  3. How to Count String Occurrence in String

How to Count String Occurrence in String

You can count the string occurrence in a string by counting the number of times the string present in the string. Here we suggest two working solutions.

match()

One of the solution can be provided by the match() function, which is used to generate all the occurrences of a string in an array. By counting the array size that returns the number of times the substring present in a string.

The global (g) in the regular expression instructs to search the whole string rather than just find the first occurrence:

w3docs logo Javascript regular expression match method
let temp = "Welcome to W3Docs"; let count = (temp.match(/to/g) || []).length; console.log(count);

If there are no matches, it will return null:

w3docs logo Javascript regular expression match method
let temp = "Welcome to W3Docs"; let count = temp.match(/is/g); console.log(count);

split()

There is another solution provided by string.prototype.split() which splits the string and determine the count by using the length of the resulting array:

w3docs logo Javascript split method
let theString = "Welcome to W3Docs"; console.log(theString.split("to").length - 1);

The String.prototype.match() method

The match() method retrieves the output of matching a string against a regex. It returns an array whose contents depend on the presence or absence of the global flag (g) or returns null if no matches are found. If the regex does not include the g flag, the str.match()method will return the same result as RegExp.exec().

The String.prototype.split() method

The split() method cuts a string into an ordered set of substrings, puts these substrings into an array, and returns an array. The division is achieved by searching for a pattern, where it is provided as the first parameter in the call of the method. It returns an array of strings split at each point where the separator occurs. The separator can be a either a string or regex.

Do you find this helpful?