How to check if one string contains another substring in JavaScript?
Usually, I would expect a
String.contains()
method, but there doesn't seem to be one. What is the reasonable way to check for this?Answer :
Here is a list of current possibilities:
1. indexOf - (see bottom)
2. (ES6) includes - go to answer, or this answer
var string = "foo",
substring = "oo";
string.includes(substring);
3. search - go to answer
var string = "foo",
expr= "/oo/";
string.search(expr);
4. lodash includes - go to answer
var string = "foo",
substring = "oo";
_.includes(string, substring);
5. RegExp - go to answer
var string = "foo",
expr= "/oo/";
expr.test(string);
6. Match - go to answer
var string = "foo",
expr= "/oo/";
string.match(expr);
Performance tests (http://jsben.ch/#/RVYk7) are showing that indexOf might be the best choice, if it comes to a point where speed matters.
Outdated answer:
String.prototype.indexOf
returns the position of the string in the other string. If not found, it will return -1
:var string = "foo",
substring = "oo";
console.log(string.indexOf(substring) !== -1);
COMMENTS