How to verify that a string has a substring in JavaScript?

· · 1722 views

Is there any method to check if string has a substring something like String.contains('some string').

0
2 Answers

In ECMAScript 6 has String.prototype.includes:

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

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

Old browsers do not support includes. So for old browsers use String.prototype.indexOf that returns -1 if a substring not found:

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

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

There is a String.prototype.includes in ES6:

"potato".includes("to");
> true

Note that this does not work in Internet Explorer or some other old browsers. To make it work in old browsers use following snippet:

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;
    }
  };
}
0

Please login or create new account to participate in this conversation.