~Onlooker 2009-11-24 13:04 采纳率: 0%
浏览 778
已采纳

如何检查一个字符串是否包含子字符串在 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

  • 写回答

29条回答 默认 最新

  • Lotus@ 2009-11-24 13:05
    关注

    Here is a list of current possibilities:

    1. (ES6) includesgo 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. searchgo to answer

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

    4. lodash includesgo to answer

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

    5. RegExpgo to answer

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

    6. Matchgo 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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(28条)

报告相同问题?

悬赏问题

  • ¥15 求差集那个函数有问题,有无佬可以解决
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥65 汇编语言除法溢出问题