【问题标题】:Extracting url path using regexp使用正则表达式提取 url 路径
【发布时间】:2014-12-04 10:54:35
【问题描述】:

场景

我想从 document.location 中提取路径字符串,不包括前导斜杠。 例如,如果 url 是:

http://stackoverflow.com/questions/ask

我会得到:

questions/ask

这应该很简单:

/* group everything after the leading slash */
var re = /\/(.+)/gi;
var matches = document.location.pathname.match(re);
console.log(matches[0]);

但是,如果我在 firebug 控制台中运行这个 sn-p,我仍然会得到前导斜杠。 我已经测试了regexp,正则表达式引擎正确提取了组。

问题

如何正确获取第 1 组字符串?

【问题讨论】:

    标签: javascript regex regex-group


    【解决方案1】:

    如果您只想获取不带前导斜杠的路径名,则不需要正则表达式。由于location.pathname 总是以/ 开头,因此您可以简单地从第一个索引中获取子字符串:

    document.location.pathname.substr(1) // or .slice(1)
    

    【讨论】:

      【解决方案2】:

      你说的是斜线还是斜线?从您的帖子来看,它看起来像前导斜线。

      document.location.pathname.replace(/^\//,"")
      

      顺便说一句,您的正则表达式是正确的,但您只需删除gi 并读取matches[1] 而不是matches[0],因为matches[0] 是整个字符串匹配正则表达式,而matches[1] 是在匹配的字符串中捕获的部分(正则表达式中带括号的引号)。

      var matches = document.location.pathname.match(/\/(.+)/);
      console.log(matches); // ["/questions/ask", "questions/ask"]
      

      【讨论】:

        【解决方案3】:

        使用正则表达式可以做到:

        var m = 'http://stackoverflow.com/questions/ask'.match(/\/{2}[^\/]+(\/.+)/);
        console.log(m[1]); /questions/ask
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2013-06-03
          • 1970-01-01
          • 2021-07-29
          • 1970-01-01
          • 1970-01-01
          • 2012-07-25
          • 1970-01-01
          相关资源
          最近更新 更多