JavaScript 3 ways of Check subString contains in a string

How to find if substring exists in a given string in Javascript

check substring exists in a given string in Javascript

String checking operations is an operation every developer needs to know.
In this blog post, I will take you through several ways of checking whether a substring exists in a given string in JavaScript.

  • ES5 String indexOf() method
  • Inbuilt String search() method
  • Using ES6 String includes() method

ES5 String indexOf method

Before ES6, the indexOf method was used to check substring presence in the main string. It returns -1 if the string is not found, or else the positional index of the first occurrence of a given substring.


Input and return values

  • input is given substring to check the presence
  • returns number -1 or greater than 0.


let mainString = "String checking indexOf example";  
console.log(mainString.indexOf("checking")) // 7  
console.log(mainString.indexOf("asdfad")) // -1  

Let’s see one more example in conditional if the expression.

if(("first string".indexOf('string')==-1)){  
console.log('not found');  

From the above example, code looks not human readable, and conditional expression always needs an extra check against integer instead of simply true or false values. So check integer values if the conditional expression is disadvantaged.

String Search with regular expression

It is one more way of checking string exists or not.

It checks the regular expression against a given string object and returns positional index, else not found, returns -1.

String.search(regular expression)  

the return type is an index of matched starting positions.
input accepted is a regular expression.

let string = "search string example";  
console.log(string.search('string') !== -1); // true  
console.log(string.search('string') !== -1); // true  
console.log(string.search('string')) // outputs 7  

The disadvantage is regular expression processing takes more time and resources, It is not advisable to use this for simple use cases.

ES6 String includes a method

ES6 is a new JavaScript feature introduced in the 2015 year. The string includes() a new method that returns true if a given substring contains in a string. Syntax



  • substring - This is string text which checks for existence in a given string
  • index - starting position at which checking starts from, and optional
  • Returns true - if substring found false - not found in a given string Here is an example.
const message = "Substring checking example";  
console.log(message.includes("example")); // true  
console.log(message.includes("aserwerew")); // false  
console.log(message.includes("as", 8)); // false  
console.log(message.includes("string", 3)); // true  

Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.

Similar Posts
You'll get a notification every time a post gets published here.