How to check if a string contains a substring in JavaScript

String.prototype.contains()

ES6 browsers support a String.prototype.contains() method.

But its not supported in older browsers still in use, such as Internet Explorer 11 and below, or Safari 7 and below.

var string1 = "topjavatutorial";
var string2 = "java";

if (string1.contains(string2)) {
console.log('string1 contains string2');
}

 
If you are still one of those browsers, we can use the following functions :

indexOf()

var string1 = "topjavatutorial";
var string2 = "java";
if(string1.indexOf(string2) != -1){
    console.log("string1 contains string2");
}
else{
    console.log("string1 doesn't contain string2");
}

Output :

string1 contains string2
 

search()

We can use javascript search() method to check if a string contains a substring.

search() returns position of the match, or -1 if no match found.

if(string1.search(string2) != -1){
    console.log("string1 contains string2");
}

 

© 2017, https:. All rights reserved. On republishing this post, you must provide link to original post

Leave a Reply.. code can be added in <code> </code> tags