【问题标题】:trouble with getting RegExp to work [duplicate]让 RegExp 工作的麻烦[重复]
【发布时间】:2017-09-02 05:31:43
【问题描述】:

我正在尝试在 javascript 中使用正则表达式,但我无法让任何东西发挥作用

        var pattern = new RegExp('http');
        var hi = "http://hi.m3u8";
        console.log(hi.indexOf(pattern));

这是返回-1?即使变量 hi 中肯定有一个 http 所以呢?知道我可能做错了什么吗?

【问题讨论】:

    标签: javascript regex


    【解决方案1】:

    当使用regex 时,您应该使用matchtest 而不是indexOf,但在您的情况下使用正则表达式没有意义。使用indexOf 就足够了:

    var pattern = 'http';
    var hi = "http://hi.m3u8";
    console.log(hi.indexOf(pattern));

    【讨论】:

      【解决方案2】:

      正则表达式是这样测试的

          var pattern = new RegExp('http');
              var hi = "http://hi.m3u8";
              console.log(pattern.test(hi));

      【讨论】:

        猜你喜欢
        • 2011-08-15
        • 1970-01-01
        • 1970-01-01
        • 2021-08-17
        • 1970-01-01
        • 2023-03-09
        • 2017-01-11
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多