How to check whether a string contains a substring in JavaScript

ES6 introduced String.prototype.includes:

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

includes doesn’t have IE support, though. In an ES5 or older environment, String.prototype.indexOf, which returns −1 when it doesn’t find the substring, can be used instead:
var string = "foo",
substring = "oo";
string.indexOf(substring) !== -1

Note that this does not work in Internet Explorer or some other old browsers with no or incomplete ES6 support. To make it work in old browsers, you may wish to use a transpiler like Babel, a shim library like es6-shim, or this polyfill from MDN:
if (!String.prototype.includes) {
String.prototype.includes = function(search, start) {
'use strict';
if (typeof start !== 'number') {
start = 0;
if (start + search.length > this.length) {
return false;
} else {
return this.indexOf(search, start) !== -1;

2019-05-11 21:18:45


Add a Comment

Login or Register to post a Comment.