Usually I would expect a String.contains()
method, but there doesn't seem to be one.
What is a reasonable way to check for this?
转载于:https://stackoverflow.com/questions/1789945/how-to-check-whether-a-string-contains-a-substring-in-javascript
Usually I would expect a String.contains()
method, but there doesn't seem to be one.
What is a reasonable way to check for this?
转载于:https://stackoverflow.com/questions/1789945/how-to-check-whether-a-string-contains-a-substring-in-javascript
Here is a list of current possibilities:
1. (ES6) includes
—go to answer
var string = "foo",
substring = "oo";
string.includes(substring);
2. ES5 and older indexOf
var string = "foo",
substring = "oo";
string.indexOf(substring) !== -1;
String.prototype.indexOf
returns the position of the string in the other string. If not found, it will return -1
.
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/; // no quotes here
expr.test(string);
6. Match—go to answer
var string = "foo",
expr = /oo/;
string.match(expr);
Performance tests are showing that indexOf
might be the best choice, if it comes to a point where speed matters.