HiveBrain v1.2.0
Get Started
← Back to all entries
snippetjavascriptCritical

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

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
howcheckwhethersubstringstringjavascriptcontains

Problem

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?

Solution

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

Context

Stack Overflow Q#1789945, score: 16083

Revisions (0)

No revisions yet.