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:
trueCase-insensitive search
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:
trueFinding 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:
7One 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:
trueCommon 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
foundFunctions used in this recipe
- String.prototype.includes — Checks whether a string contains a given substring.
- String.prototype.indexOf — Finds the position of the first occurrence of a substring.
- String.prototype.toLowerCase — Converts a string to lowercase.