ECMAScript 6 introduced String.prototype.includes:
const string = "foo";
const substring = "oo";
console.log(string.includes(substring)); // true
String.prototype.includes is case-sensitive and is not supported by Internet Explorer without a polyfill.
In ECMAScript 5 or older environments, use String.prototype.indexOf, which returns -1 when a substring cannot be found:
var string = "foo";
var substring = "oo";
console.log(string.indexOf(substring) !== -1); // true
ECMAScript 6 introduced String.prototype.includes:
const string = "foo";
const substring = "oo";
console.log(string.includes(substring)); // true
String.prototype.includes is case-sensitive and is not supported by Internet Explorer without a polyfill.
In ECMAScript 5 or older environments, use String.prototype.indexOf, which returns -1 when a substring cannot be found:
var string = "foo";
var substring = "oo";
console.log(string.indexOf(substring) !== -1); // true
There is a String.prototype.includes in ES6:
"potato".includes("to");
> true
Note that this does not work in Internet Explorer or some other old browsers with no or incomplete ES6 support. To make it work in old browsers, you may wish to use a transpiler like Babel, a shim library like es6-shim, or this polyfill from MDN:
if (!String.prototype.includes) {
String.prototype.includes = function(search, start) {
'use strict';
if (typeof start !== 'number') {
start = 0;
}
if (start + search.length > this.length) {
return false;
} else {
return this.indexOf(search, start) !== -1;
}
};
}