This post will discuss how to find the matches of a substring in a string with JavaScript.

1. Using Regular expression

We can use the match() function to find the substring matches in a string. This function takes a regular expression and returns an array containing all matches in the string. For finding all matches within the string, we can use the regular expression with global flag g . Since match() function returns an array, we can use the length property to get a count of the number of matches from the returned array. Here’s an example of this approach:

Download  Run Code

 
The above code will only get the number of matches from the returned array. To get the index of all matches of the substring in a string, we can call the exec() function of the regular expression object. It takes a string as an argument and returns an object with match information, or null in case of no match. We can can use this function within a loop and update the lastIndex property of regex object at each iteration of the loop, until no more matches are found. For example, we can use something like this:

Download  Run Code

2. Using indexOf() function

A non-regex solution is to use the String.indexOf() function, which takes a substring and returns the index of the first occurrence of it within the string, or -1 if the substring is not found. To find all the matches of the substring, we can call the indexOf() function repeatedly using a loop and keep track of the last position in the string in loop index variable. For example, using the same string and substring as before, we can find all the matches of the substring using indexOf() like this:

Download  Run Code

3. Using slice() function

The idea here is to loop through the string from the first character to the last, and extract the part of the string that starts from that index and having the same length as the substring, and compare it with the substring. Do this for every index using the slice() function, and count the matches. Here is an example of how to use this method:

Download  Run Code

That’s all about finding the matches of a substring in a string with JavaScript.