How to search for a string in JavaScript?

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 within another string.

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

The syntax is :;

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:

var str = "I like Pizza a lot. Preferably a smoked chicken pizza.";"Pizza"); //returns 7"pizza"); // returns 48; // returns 7 as the RegEx param " i " would make the search case insensitive.

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 occurrences 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:

function getStrIndexes(str, searchStr) {
    var re = new RegExp(searchStr, "gi"),
        SearchIndex = [], match;

    while (match = re.exec(str)) {

    return SearchIndex;

console.log(getStrIndexes("I like Pizza a lot. Preferably a smoked chicken pizza.", "pizza"));
// returns [7,48]

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.