How to check whether a string contains a substring in JavaScript?
Javascript | string | substring | indexOf | includes | how to
ECMAScript 6 introduced String.prototype.includes:
const string = "Hello World!";
const substring = "World";
console.log(string.includes(substring)); // true
Note: includes
doesn’t have Internet Explorer support. In ECMAScript 5 or older environments, use String.prototype.indexOf
, which would return -1 when a substring cannot be found:
var string = "Hello World!";
var substring = "Hello";
console.log(string.indexOf(substring) !== -1); // true
includes
andindexOf
performs a case-sensitive search