/ JAVASCRIPT, FRONT-END

How to check whether a string has a substring in Javascript

Question:

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

Answer:

There are few ways to solve this problem. See below for more details.

One: use indexOf

var string = "foo",
    substring = "oo";
string.indexOf(substring) !== -1;

indexOf will find the index position of this substring, if not found, will return -1

Two: use includes

var string = "foo",
    substring = "oo";
string.includes(substring);
var string = "foo",
    expr = /oo/;
string.search(expr);

Four: use lodash includes

var string = "foo",
    substring = "oo";
_.includes(string, substring);

Five: use RegExp

var string = "foo",
    expr = /oo/;  // no quotes here
expr.test(string);

Six: use Match

var string = "foo",
    expr = /oo/;
string.match(expr);

Reference


This is the end of post