How to Check if a String Contains a Substring in JavaScript

In this article, we look at multiple ways to quickly check if a string contains a substring in JavaScript.

1. String includes() Method

To check if a string contains a substring, we can call the includes() method on the string, passing the substring as an argument e.g., str.includes(substr). The includes() method returns true if the string contains the substring, otherwise, it returns false.

const str = 'Bread and Milk';

const substr1 = 'Milk';
const substr2 = 'Tea';

console.log(str.includes(substr1)); // true

console.log(str.includes(substr2)); // false

Tip

To perform a case-insensitive check, convert both the string and the substring to lowercase before calling includes() on the string.

const str = 'Bread and Milk';

const substr = 'milk';

console.log(
  str.toLowerCase().includes(substr.toLowerCase())
); // true

2. String indexOf() Method

We can also use the indexOf() method to check if a string contains a substring. We call the indexOf() method on the string, passing the substring as an argument. Then we compare the result with -1. For example:

const str = 'Bread and Milk';

const substr1 = 'Milk';
const substr2 = 'Tea';

console.log(str.indexOf(substr1) > -1); // true

console.log(str.indexOf(substr2) > -1); // false

The indexOf() method searches a string for a value and returns the index of the first occurrence of that value. If the value can’t be found, it returns -1.

const str = 'Bread and Milk';

const substr1 = 'Milk';
const substr2 = 'Tea';

console.log(str.indexOf(substr1)); // 10
console.log(str.indexOf(substr2)); // -1

This is why we compare the result of indexOf() with -1 to check if the substring is in the string.

Tip

To perform a case-insensitive check, convert both the string and the substring to lowercase before calling indexOf() on the string.

const str = 'Bread and Milk';

const substr = 'milk';

console.log(
  str.toLowerCase().indexOf(substr.toLowerCase()) > -1
); // true

3. Regex Matching

We can test the string against regex patterns to determine if it contains a substring. One way to do this is using the RegExp test() method.

const str = 'Bread and Milk';

console.log(/Milk/.test(str)); // true
console.log(/Tea/.test(str)); // false

Using regex matching allows us to easily specify complex patterns to search the string for.

const str = 'Bread and Milk';

// Contains 'sand', 'land', or 'and'?
console.log(/[sl]?and/.test(str)); // true

// Contains 'book0', 'book1', ..., 'book8' or 'book9'?
console.log(/book(\d)/.test(str)); // false


11 Amazing New JavaScript Features in ES13

This guide will bring you up to speed with all the latest features added in ECMAScript 13. These powerful new features will modernize your JavaScript with shorter and more expressive code.

11 Amazing New JavaScript Features in ES13

Sign up and receive a free copy immediately.

Leave a Comment

Your email address will not be published. Required fields are marked *