How to check if a string contains substring javascript?
I'm looking for a function to check if a substring is present in a given string. I have tried other options like contains which doesn't work. Please help
1 Answer
5 years ago by Jahaan
Below are the couple of ways to check if a substring is present in a given string.
1. includes()
ES6 introduced this function, and it will result either true or false. You can also specify an optional second parameter like shown below which specifies the position to start the search.
let str = "good morning";
let substr = "morning";
console.log(str.includes(substr));
console.log(str.includes(substr,5)); // optional second parameter specifies the position to start the search.
2. indexOf()
This function also used to check if substring is present in the given string and it will result either -1
(no match) or a positive index value of the sub-string. You can also specify an optional second parameter like shown below which specifies the position to start the search.
let str = "good morning";
let substr = "good";
console.log(str.indexOf(substr));
console.log(str.indexOf(substr,5)); // optional second parameter specifies the position to start the search.
5 years ago by Divya