How to check whether a string contains a substring in JavaScript?

const string = "foo"; const substring = "oo"; console.log(string.includes(substring));

Usually I would expect a String.contains() method, but there doesn't seem to be one.

What is a reasonable way to check for this?

✔️✔️✔️ Answer

ECMAScript 6  introduced String.prototype.includes:

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

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

Expand snippet

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:

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

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

Expand snippet

Subscribe to Farath Shba

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
jamie@example.com
Subscribe