In this tutorial, I am going to show you a very simple, fast, and modern(ES6) way to check whether a string contains a substring in JavaScript.
String.prototype.includes()
method checks if one string may be found within another string. It returns a boolean value of true
if the string is found, otherwise false
.
Old way: Before ES6,
String.prototype.indexOf()
method was used to check whether a string contains a substring, which returns -1 when a substring cannot be found.
Let’s say you following string
To check whether variable title
contains string Intelligent
, we can use String.prototype.includes()
as follows
Now, if you console.log the textIsPresent
variable, you should get the output as true
The includes()
method is case sensitive i.e. it would return false
if you check the inclusion of string intelligent in title
string.
Quick Links