How to check if a String Contains a Substring in Javascript

 In many Scenarios we may need to write the javascript code to check If a String Contains a give SubString.

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 Object     var re = new RegExp("ab+c");

Below is the Simple Example to check If a String Contains the another String


var str = "javascriptfoo";
var re = new RegExp("foo");
console.log(re.test(str));
Above code will return true.

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";
var str1 = "foo";
console.log( str.indexOf(str1));
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.

To find different ways of using Regular expression This Mozilla article is very good for reference purpose.

No comments:

Post a Comment