hurriedly% 2009-11-24 13:04 采纳率: 100%
浏览 1134
已采纳

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

  • 写回答

30条回答 默认 最新

  • 乱世@小熊 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.

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

报告相同问题?

悬赏问题

  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料
  • ¥15 使用R语言marginaleffects包进行边际效应图绘制
  • ¥20 usb设备兼容性问题
  • ¥15 错误(10048): “调用exui内部功能”库命令的参数“参数4”不能接受空数据。怎么解决啊
  • ¥15 安装svn网络有问题怎么办
  • ¥15 Python爬取指定微博话题下的内容,保存为txt
  • ¥15 vue2登录调用后端接口如何实现
  • ¥65 永磁型步进电机PID算法
  • ¥15 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?