The String data type must be the most common data type that we use in JavaScript. One of the most common functionality around string that we would have come across is to search for a string/character/word withing another string.

You can easily search for a word in javaScript using the string.search() method of JavaScript.

The syntax is :

string.search(searchString);

The parameter searchString can be a string or a RegExp(Regular Expression). Using RegExp along with the searchString would help in doing a case-insensitive search.

Let’s take a look at an example:

You may notice that in all the cases in the above example, we get index of just a single occurence of the string. Well, keep reading if that’s what you are wondering about.

Then, how to search for multiple occurrences of a string/word in JavaScript ?

I understand that a majority of us would have scenarios where we need to check for multiple occurences of a string/word. While there is no existing JavaScript APIs to do that, we can achieve it easily using RegExp. Look at the following example:

In the example above, on line 2 we are creating a new RegExp pattern and passing parameters “g” and ” i “. This tells RegExp to match against the whole string and in a case-insensitive manner. The return value would be an Array of the multiple index found. So now you just need to call the above mentioned function with the string and the search string as the parameter and it would return you an Array of the index numbers at which the string was found.

Hope this article has been helpful to you. Do let us know your comments.