How to check if a string contains a substring in JavaScript
Created
Modified
Using String.prototype.includes
The includes() method performs a case-sensitive search to determine whether one string may be found within another string, returning true or false as appropriate.
'Google Docs will start'.includes('Docs'); // => true
// includes return true for empty substring
'Google Docs will start'.includes(''); // => true
// case-sensitive
'Google Docs will start'.includes('docs'); // => false
String.prototype.indexOf
includes doesn’t have Internet Explorer support, though. In ECMAScript 5 or older environments, use String.prototype.indexOf, which returns -1 when a substring cannot be found.
'Google Docs will start'.indexOf('Docs') !== -1; // => true
// an empty string is a substring of every string
'Google Docs will start'.indexOf('') !== -1; // => true
// case-sensitive
'Google Docs will start'.indexOf('Docs') !== -1; // => false
Polyfill
if (!String.prototype.includes) {
String.prototype.includes = function(search, start) {
'use strict';
if (search instanceof RegExp) {
throw TypeError('first argument must not be a RegExp');
}
if (start === undefined) { start = 0; }
return this.indexOf(search, start) !== -1;
};
}