【问题标题】:Regex to find id in url正则表达式在 url 中查找 id
【发布时间】:2011-05-24 22:05:57
【问题描述】:

我有以下网址:

http://example.com/product/1/something/another-thing

虽然也可以:

http://test.example.com/product/1/something/another-thing

http://completelydifferentdomain.tdl/product/1/something/another-thing

我想使用 Javascript 从 URL 中获取数字 1(id)。

唯一不变的是/product。但我还有一些其他页面,其中 url 中也有 /product,只是不在路径的开头。

正则表达式会是什么样子?

【问题讨论】:

    标签: javascript regex match


    【解决方案1】:
    1. 使用window.location.pathname 检索当前路径(不包括 顶级域名)。

    2. 使用 JavaScript 字符串 match 方法。

    3. 使用正则表达式 /^\/product\/(\d+)/ 查找以 /product/ 开头的路径,然后是一个或多个数字(在末尾添加 i 以支持不区分大小写)。

    4. 想出这样的东西:

      var res = window.location.pathname.match(/^\/product\/(\d+)/);
      if (res.length == 2) {
          // use res[1] to get the id.
      }
      

    【讨论】:

      【解决方案2】:

      /\/product\/(\d+)/ 并获取$1

      【讨论】:

      【解决方案3】:

      只是,作为替代方案,在没有 Regex 的情况下执行此操作(尽管我承认 regex 在这里非常好)

      var url = "http://test.example.com//mypage/1/test/test//test";
      var newurl = url.replace("http://","").split("/");
      for(i=0;i<newurl.length;i++) {
          if(newurl[i] == "") {
           newurl.splice(i,1);   //this for loop takes care of situatiosn where there may be a // or /// instead of a /
          }
      }
      alert(newurl[2]); //returns 1
      

      【讨论】:

      • 替换函数中的搜索字符串是否接受数组?对于我以后想去https://的情况?
      • @PeeHaa 不是我所知道的,但你自然可以在上面链接另一个替换功能url.replace("http://","").replace("https://","")...
      【解决方案4】:

      我想建议另一种选择。

      .match(/\/(\d+)+[\/]?/g)
      

      这将返回 id 的所有匹配项。

      例子:

      var url = 'http://localhost:4000/#/trees/8/detail/3';
      
          // with slashes
          var ids = url.match(/\/(\d+)+[\/]?/g);
          console.log(ids);
      
          //without slashes
          ids = url.match(/\/(\d+)+[\/]?/g).map(id => id.replace(/\//g, ''));
          console.log(ids);

      这样,您的 URL 甚至都无关紧要,它只是检索所有只有数字的部分。

      要获得第一个结果,您可以删除 g 修饰符:

       .match(/\/(\d+)+[\/]?/)
      

      var url = 'http://localhost:4000/#/trees/8';
      
      
      var id = url.match(/\/(\d+)+[\/]?/);
      //With and without slashes
      console.log(id);
      没有斜杠的 id 将在第二个元素中,因为这是在完整匹配中找到的第一个组。

      希望这对人们有所帮助。 干杯!

      【讨论】:

        猜你喜欢
        • 2016-12-31
        • 1970-01-01
        • 2011-07-24
        • 2015-04-02
        • 2011-05-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-11-01
        相关资源
        最近更新 更多