Check if a String contains a Substring in JavaScript

avatar

Borislav Hadzhiev

Sun Oct 03 20212 min read

banner

Photo by Jessie McCall

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

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

index.js
// Not Supported in IE 6-11 const string = 'hello world'; const substring = 'hello'; console.log(string.includes(substring)); // ๐Ÿ‘‰๏ธ true if (string.includes(substring)) { // ๐Ÿ‘‰๏ธ substring is contained in string }

In the example, we've invoked the String.includes method with a substring.

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
// Supported in IE 6-10 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

In the code snippet, the substring is contained in the string, starting at index 0, therefore the indexOf method returns 0.

The code block of our if conditional check does not run if String.indexOf returns -1, which happens when the substring is not contained in the string.

If you have to support Internet Explorer and you don't use a polyfill, it's best to use the String.indexOf method. In any other case the String.includes method is much more intuitive and readable.

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee