We will be using this logic of indexOf() method to check a string contains another sub-string. This code is simple and easy to understand. You can check the demo below followed by the code snippet.
Enter Main String:<input id="test" type="text" value=""><br/>
Sub String To Compare:<input id="test1" type="text" value="">
<input type="submit" value="submit" onclick="get();">
var str = document.getElementById("test").value;
var substr = document.getElementById("test1").value;
if (str.indexOf(substr) !== -1)
alert("The string ' " + str + " ' contains the substring ' " + substr + " '!");
alert("The string ' " + str + " ' does not contain the substring ' " + substr + " '!");
We create a form, where we take the strings to be compared as inputs. When the form is submitted, we call the function get(). Where we get the values of the input strings as “str” and “substr”.
We use an if look where we use the indexOf() function to compare the two strings not equal to -1, then it contains the substring from first string else it doesn’t.
Hope you enjoyed the snippet, if you have any doubts or suggestions please let us know by commenting below.