• Post category:JavaScript
  • Reading time:4 mins read

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.

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.

var str = 'codepremix';
str.includes('code');
// Output: true

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

var str = 'CodePremix';
str.includes('code');
// Output: false

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

str.includes(substr, 30);

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.

var str = 'codepremix';
str.indexOf('premix');
// Output: 4

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.

var str = 'The string contains the substring';
str.indexOf('string',15);
// Output: 27

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.

var str = 'The string contains the substring';
var reg = /String/i;  // i flag for case-insensitive
var pos = str.search(reg);
console.log(pos);
// Output: 4

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

Leave a Reply