How to Check Whether a String Contains a Substring in JavaScript?



In this post, we will learn how to check whether a String contains a Substring in JavaScript?.

Example - Check Whether a String Contains a Substring in JavaScript?

ECMAScript 6 introduced String.prototype.includes:

const string = "foo";
const substring = "oo";

console.log(string.includes(substring)); // true

String.prototype.includes function 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:

var string = "foo";
var substring = "oo";

console.log(string.indexOf(substring) !== -1);

Comments