How To Check If A String Contains A Substring In JavaScript

How To Check If A String Contains A Substring In JavaScript

One of the many common scenarios encountered during web application development is checking if a string contains a substring in JavaScript. In this tutorial, you’ll see a couple of ways to find a substring from a string using JavaScript.

Other tutorials in JavaScript Array series.

Methods To Check If A String Contains A Substring

Using indexOf

You can use the String.indexOf method to find a substring in a string using JavaScript. indexOf methods returns a index greater than 0 if the substring is present in the string. If the substring is not found it will return -1. Here is a code which demonstrate the same :

var position = 'codehandbook'.indexOf('hand')
console.log('substring starts at index ', position)

The above code will display the following output:

// output
"substring starts at index " 4

So if indexOf method returns -1 the substring is not found and if it returns a value greater than -1 the substring is found.

Using RegExp

You can use regular expressions to check if a string contains a substring. For this to work you need to create a regular expression using your search string and test it against the main string. Here is the JavaScript code which shows the same :

var mainString = 'codehandbook'
var substr = /hand/
var found = substr.test(mainString)
if(found){
  console.log('Substring found !!')
} else {
  console.log('Substring not found !!')
}

As seen in the above code, you have converted the search term into a regular expression and used the test method to test if the substring if found.

Using Includes

You can check if a string contains a substring using the includes method. It returns true if the substring is found and false if the substring is not found. Here is a JavaScript code sample :

var found = 'codehandbook'.includes('hand')
if(found){
  console.log('Substring found !!')
} else {
  console.log('Subtring not found !!')
}

The above code will have the following output :

// output
"Substring found !!"

Wrapping It Up

In this tutorial you learnt different methods to check if a string contains a substring in JavaScript. Have you used the above methods or any other different approach for finding if a string contains a substring ? Do let us know your thoughts in the comments below.