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

1
2
3
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

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

Four: use lodash includes

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

Five: use RegExp

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

Six: use Match

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

Reference


This is the end of post