Home » Javascript » How to check if a string contains a substring in Javascript

How to check if a string contains a substring in Javascript

To remove text from a string in javascript, you’ll first need to know how to check if the string contains the substring or character. I’ll start by explaining how to find out if the string contains the other substring, and then we will remove the substring from the main string, all using Javascript. For instance if you are trying to work out whether the word ‘beer’ is in this sentence – ‘The drinks order contains a beer and a wine‘, or you might be searching for a character like ‘*’ in a string of data, this post will explain how to do that.

Check if string contains substring

If you want to find a substring within another string, the best way to do it in Javascript is using indexOf:

var mainString = "They have ordered some wine and two beers on table 42";
var substring = "beer";

console.log(string.indexOf(substring) !== -1);
//This will print true. If the string is NOT found in the main string,
//then indexOf will return -1. So by checking it does NOT equal -1,
//we get true for a match.

You will find some people saying you can use string.includes("beer") but that isn’t supported by Internet Explorer, whereas indexOf is. It’s frustrating because string.includes is infinitely more readable but there you go.

What does indexOf really do?

IndexOf tells us not only if a string exists in another string, it also tells us the character position of the first instance of the string you’re searching for, more precisely:

  • If the subString is NOT found in the main string, it returns -1.
  • If the subString IS found in the main string, it returns the position of the first instance of the subString.
	let orderText = "Order 42: red wine, beer, white wine";

    //Example 1: found once
    let substring1 = "beer";
    let result1 = orderText.indexOf(substring1);
    console.log("Result is :" + result1);
    //Result is :20

    //Example 2: found twice
    let substring2 = "wine";
    let result2 = orderText.indexOf(substring2);
    console.log("Result is :" + result2);
    //Result is :14

    //Example 3: not found
    let substring3 = "coke";
    let result3 = orderText.indexOf(substring3);
    console.log("Result is :" + result3);
    //Result is :-1

In the third example here it shows that if the sub string exists twice in the main string, then indexOf gives us the position of the first instance.

It’s important to note that an indexOf search is case sensitive, illustrated in this example, where the lowercase ‘me’ is found, but the uppercase ‘ME’ is not:

    let mainString = "Hello, is it me you're looking for?";
    let substring1 = "me";
    let substring2 = "ME";

    let result1 = mainString.indexOf(substring1);
    let result2 = mainString.indexOf(substring2);

    console.log("Result1 is :" + result1);
    console.log("Result2 is :" + result2);
    //Result1 is :13
    //Result2 is :-1

If you want your string search to be case insensitive then convert both the main string and the substring to lowercase using string.toLowerCase() before doing the search.

 	let substring2 = "ME";
    let result2 = mainString.toLowerCase().indexOf(substring2.toLowerCase());
    console.log("Result2 is :" + result2);
	//Result2 is :13

In the image below I’ve highlighted which part is which when using indexOf to find a string in a string.

how to find a character or string in a string in javascript

If indexOf tells us the position of the first instance of a substring, how can we find all occurrences of a substring in a string in Javascript?

Find all occurrences of a substring in a string

The indexOf method has a second, optional property, which is ‘position’, or rather the position to start searching the string from. If you don’t specify anything it defaults to 0, which is the start of the string you’re searching.

	let substring1 = "wine";
    let position = 0;
    let result1 = orderText.indexOf(substring1, position);
	console.log("Result is :" + result1);
    //Result is :14

So in order to find all instances of a string or character in another string, we can set a new position each time we find a match. Here’s an example:

	let substring1 = "wine";
    let position = 0;
    let result1 = orderText.indexOf(substring1, position);

    console.log("Result is :" + result1);
    //Result is :14, which is the position of the first instance of 'wine'

	//Now we set a new position
    position = 20;
    result1 = orderText.indexOf(substring1, position);

    console.log("Result is :" + result1);
    //Result is :32, which is the position of the second instance of 'wine', 
	//because this time we started searching at a character position after 
	//the first instance

    

By using this technique we can find a count of how many occurrences of a string there are.

    let mainString = "*a *b *c *d $e $f *";
    let searchFor = "*";
    let pos = 0; // Position Ref
    let result = []; // Final output of all index's.
    let stringToSearchIn = mainString.toLowerCase();

    // Loop to check all occurrences
    while (stringToSearchIn.indexOf(searchFor, pos) != -1) {
      result.push(stringToSearchIn.indexOf(searchFor, pos));

      pos = stringToSearchIn.indexOf(searchFor, pos) + 1;
    }

    console.log("Final ", result);
    console.log("Number found :", result?.length);

Running the above code, and viewing the console, you will see:

By using arrayName.length, we can find how many times the string was found.

In summary – using Javascript to search for a string

This post has shown how to check if a string contains a substring in JavaScript using indexOf, along with examples showing how to find the position of the first occurrence of the string or character, and finally how to find how many occurrences there are of the character or substring. You may also find my other post useful, as it explains how to find a string or an object in an Array using JavaScript. Happy searching!