Check if a string contains a substring in JavaScript

Today we’ll explain to you how to check if a string contains a substring in JavaScript. It is very simple to do this task in JavaScript.

You can also check the similar articles on String and Array.

Ways to check if a string contains a substring

  1. includes() method
  2. indexOf() method
  3. search method

1. includes() method

We can use the includes() method to check if a string contains a substring in JavaScript. This method returns the true if a substring found in a string otherwise returns false.

Note that this is case-sensitive search, so the following example returns false.

Also, in this method we can pass a second parameter that defines which index to start the search. The syntax look like below:

If you know that the first 30 characters do not include a substring then you can use the above method.

2. indexOf() method

The indexOf() method is like the includes() method but difference is the includes() method returns the boolean value and indexOf() method returns the position of the substring starting from the left. It returns -1 if it is not found.

This method is also case-sensitive and returns the 0 based index position.

Also, you can pass an optional second parameter to define the index to start the search like below.

3. search method

The search method is similar to the indexOf() method that returns the position of the substring. It is a case-insensitive method and its required single parameter as string or regular expression.

That’s it for today.
Thank you for reading. Happy Coding..!!

If you found value in this article,
you can support us by buying me a coffee! ☕

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *