Matheus Mello

Berlin, Germany

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

Cover Image for How to check whether a string contains a substring in JavaScript?
Matheus Mello
Matheus Mello
There are a few ways to check if a string contains a substring, one of these ways is using regular expressions (regex), and a different one is using the method includes which was introduced in ECMAScript 6.ECMAScript 6 introduced String.prototype.includes: const string = "foo"; const substring = "oo"; console.log(string.includes(substring)); // trueString.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);


More Stories

Cover Image for Convert Array of Numbers to Array of Strings in JavaScript

Convert Array of Numbers to Array of Strings in Ja ...

Convert Array of Numbers to Array of Strings in JavaScript...

Matheus Mello
Matheus Mello
Cover Image for Check if specific Text exists on the Page using JavaScript

Check if specific Text exists on the Page using Ja ...

Check if specific Text exists on the Page using JavaScript...

Matheus Mello
Matheus Mello
Cover Image for Check if String contains at least one Number in JavaScript

Check if String contains at least one Number in Ja ...

Check if String contains at least one Number in JavaScript...

Matheus Mello
Matheus Mello