Though there are many methods available to find a substring in JavaScript, Below are the 2 popular ways to check if a String contains SubString.
- Regular expression
- indexof
Regular expression
Using Regular Expressions to find a Substring is more appropriate way compared to indexof. because you can use specific pattern to search a string, which you cannot do using indexof.Let us see some example on Regular Expression.
Regular Expression Can be created using any of the follwing way
Using litteral Expression var re = /ab+c/;
or using RegExp Objectvar re = new RegExp("ab+c");
Below is the Simple Example to check If a String Contains the another String
Above code will return true.
var str = "javascriptfoo";
var re = new RegExp("foo");
console.log(re.test(str));
Using indexof
indexof is built in JavaScript String function, which will return the index of a substring If it contains, If it does not contain it returns -1. It is the Simplest function to check If a String contains a Substing.Example:-
var str="Javascriptfoo";Above code prints 10. So we can add check for "-1", if it is not -1 then String contains the substring and If it is "-1", then substring not present in the given string.
var str1 = "foo";
console.log( str.indexOf(str1));
To find different ways of using Regular expression This Mozilla article is very good for reference purpose.