Check if a String contains a Substring in JavaScript

avatar

Borislav Hadzhiev

Last updated: Jul 25, 2022

banner

Photo from Unsplash

Check if a String contains a Substring with String.includes #

Use the String.includes() method to check if a string contains a substring, e.g. myString.includes('substring'). The String.includes method returns true if the substring is contained in the string, otherwise false is returned.

index.js
const string = 'hello world'; const substring = 'hello'; console.log(string.includes(substring)); // 👉️ true if (string.includes(substring)) { // 👉️ substring is contained in string }

We used the String.includes method to check if a substring is contained in a string.

If the substring is contained in the string, the String.includes method returns true, otherwise it returns false.

The String.includes method is case sensitive. To do a case insensitive check if a substring is contained in a string, convert both strings to lowercase.
index.js
const string = 'HELLO world'; const substring = 'hello'; // 👇️ true console.log( string.toLowerCase().includes(substring.toLowerCase()) ); if (string.toLowerCase().includes(substring.toLowerCase())) { // 👉️ substring is contained in string }

Check if a String contains a Substring with String.indexOf #

To check if a substring is contained in a JavaScript string:

  1. Call the indexOf method on the string, passing it the substring as a parameter - string.indexOf(substring)
  2. Conditionally check if the returned value is not equal to -1
  3. If the returned value is not equal to -1, the string contains the substring
index.js
const string = 'hello world'; const substring = 'hello'; const index = string.indexOf(substring); console.log(index); // 👉️ 0 if (string.indexOf(substring) !== -1) { // 👉️ substring is contained in string }
The String.indexOf method returns the starting index of the substring, or -1 if the substring is not contained in the string.

The substring in the code sample is contained in the string starting at index 0. Therefore the indexOf method returns 0.

Our if block is only run if the String.indexOf method didn't return -1. The method only returns -1 if the substring is not contained in the string.

Which approach you pick is a matter of personal preference. I'd use the String.includes() method as it is easier to read and more direct.

Further Reading #

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.