How to Check if a String Contains a Substring in JavaScript

Last updated on June 19, 2022
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

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.

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
Coding Beauty Assistant logo

Try Coding Beauty AI Assistant for VS Code

Meet the new intelligent assistant: tailored to optimize your work efficiency with lightning-fast code completions, intuitive AI chat + web search, reliable human expert help, and more.

See also