Encodera

Thanks for reading!

Donate to the site — we work hard for you.

How to check if a string contains a substring

Short answer

The includes() method returns true when the substring is found:

console.log('Hello, world'.includes('world'));

Output:

true

The search is case-sensitive. To ignore case, convert both strings to lowercase:

const text = 'Hello, World';
 
console.log(text.toLowerCase().includes('WORLD'.toLowerCase()));

Output:

true

Finding the position

If you need to know where the substring is, use indexOf(). It returns the position or -1:

console.log('Hello, world'.indexOf('world'));

Output:

7

One of several words

To check a list of words, combine some() with includes():

const message = 'Get a free gift now';
const spamWords = ['free', 'winner', 'prize'];
 
console.log(spamWords.some((word) => message.toLowerCase().includes(word)));

Output:

true

Common mistake

indexOf() returns 0 when the substring is at the very beginning, and 0 is falsy. Do not use the result of indexOf() as a condition directly:

const text = 'Hello, world';
 
console.log(text.indexOf('Hello') ? 'found' : 'not found');
console.log(text.includes('Hello') ? 'found' : 'not found');

Output:

not found
found

Functions used in this recipe

Thanks for reading!

Donate to the site — we work hard for you.