In this article, We’ll see how to check a string contains a substring in javascript?
In ES6, we’ll use String.prototype.includes
to find a substring in a string
The includes()
method determines whether one string may be found within another string, returning true or false as appropriate.
Below an example using ES6 to find string contains a substring
var sentence = 'India is a great country.'; var word = 'great'; console.log(`The word "${word}" ${sentence.includes(word)? 'is' : 'is not'} in the sentence`); // expected output: "The word "great" is in the sentence"
In an ES5 or older environments, we’ll use String.prototype.indexOf
returns the index of a substring (or -1 if not found):
Below an example using ES5 or older environments to find string contains a substring
if (sentence.indexOf(word) !== -1) console.log('The word "' + word + '" is in the sentence'); else console.log('The word "' + word + '" is not in the sentence');
That’s it!. Please share your thoughts or suggestions in the comments below.