How to check if a string contains a substring in JavaScript
By Flavio Copes
Learn how to check if a string contains a substring in JavaScript, the modern way with the includes() method, or the pre-ES6 way with indexOf() and !== -1.
To check if a string contains a substring in JavaScript, use the includes() method. It returns true if the substring is found, false otherwise.
Checking if a string contains a substring is one of the most common tasks in any programming language, and JavaScript offers different ways to perform this operation.
The most simple one, and also the canonical one going forward, is using the includes() method on a string:
'a nice string'.includes('nice') //true
'a nice string'.includes('duck') //false
This method was introduced in ES6/ES2015.
It’s supported in all modern browsers except Internet Explorer:

To use it on all browsers, use Polyfill.io or another dedicated polyfill.
includes() also accepts an optional second parameter, an integer which indicates the position where to start searching for:
'a nice string'.includes('nice') //true
'a nice string'.includes('nice', 3) //false
'a nice string'.includes('nice', 2) //true
The check is case sensitive
includes() matches the substring exactly, including the casing:
'a nice string'.includes('Nice') //false
To perform a case-insensitive check, lowercase both strings first:
const phrase = 'A Nice String'
phrase.toLowerCase().includes('nice') //true
One edge case to know: searching for an empty string always returns true:
'a nice string'.includes('') //true
Pre-ES6 alternative to includes(): indexOf()
Pre-ES6, the common way to check if a string contains a substring was to use indexOf, which is a string method that return -1 if the string does not contain the substring. If the substring is found, it returns the index of the character that starts the string.
Like includes(), the second parameters sets the starting point:
'a nice string'.indexOf('nice') !== -1 //true
'a nice string'.indexOf('nice', 3) !== -1 //false
'a nice string'.indexOf('nice', 2) !== -1 //true
Be careful with the comparison. You must check against -1, not treat the result as a boolean.
If the substring sits at the very start of the string, indexOf() returns 0, and 0 is falsy in JavaScript:
if ('a nice string'.indexOf('a nice')) {
//never runs, indexOf() returned 0
}
This is a classic bug. The fix is the explicit !== -1 check you saw above, which works for every position.
This falsy trap is one of the reasons includes() was added to the language. It answers the question you’re actually asking, with a plain true or false, and there’s nothing to get wrong.
Related posts about js: