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
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
.
1 2 3 | var str = 'cluemediator'; str.includes('clue'); // Output: true |
Note that this is case-sensitive search, so the following example returns false
.
1 2 3 | var str = 'Cluemediator'; str.includes('clue'); // 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:
1 | 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.
1 2 3 | var str = 'cluemediator'; str.indexOf('mediator'); // 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.
1 2 3 | 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.
1 2 3 4 5 | 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..!!