如何检查字符串是否包含JavaScript中的子字符串? [英] How to check whether a string contains a substring in JavaScript?

查看:179
本文介绍了如何检查字符串是否包含JavaScript中的子字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

通常我会期望 String.contains()方法,但似乎没有。

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?

推荐答案

以下是当前可能性列表:

Here is a list of current possibilities:

1。 (ES6)包括 - 转到答案

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

2。 ES5及更早版本 indexOf

2. ES5 and older indexOf

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

String.prototype.indexOf 返回另一个字符串中字符串的位置。如果没有找到,它将返回 -1

3。 搜索 - 转到回答

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

4。 lodash包括 - 去回答

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

5。 RegExp - 去回答

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

6。匹配 - 转到答案

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






性能测试显示 indexOf 可能是最佳选择,如果它达到了速度的程度事情。


Performance tests are showing that indexOf might be the best choice, if it comes to a point where speed matters.

这篇关于如何检查字符串是否包含JavaScript中的子字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆