【问题标题】:how to get a URL parameter with regexp/javascript-method in a URL with hash-elements?如何在带有散列元素的 URL 中使用 regexp/javascript-method 获取 URL 参数?
【发布时间】:2012-10-14 18:09:26
【问题描述】:

我正在尝试从 url 中提取字符串。 URL 可以是:

http://page.de/s/project.html?id=1

http://page.de/s/project.html?id=1/#/s/project.html?id=x

我需要提取最后一个?id=-value,但我不能让它去。这就是我所拥有的:

url_snip = key.replace("?id=","")

仅适用于第一个 URL。

问题:
无论 URL 是什么,是否有 regexp 或获取最后一个 id 值的方法?

谢谢!

【问题讨论】:

    标签: javascript url parameters hashtag


    【解决方案1】:

    您可以在location.search 上使用split 提取

    var ids = window.location.search.split('&')[0].split('=');
    ids[0] //id;
     ids[1] //1
    

    【讨论】:

      【解决方案2】:

      鉴于您发布的两种表格:

      url_snip = key.substring(key.lastIndexOf('=') + 1);
      

      JS Fiddle demo (admittedly using a function, but it's the same approach).

      另一种选择,使用split()

      var parts = url.split('=');
          return parts[parts.length - 1];
      

      JS Fiddle demo.

      【讨论】:

      • @jbabey:you're wrong。如果没有第二个参数,substring() 将返回从 first 参数传递的索引开始的子字符串,直到字符串的结尾。
      猜你喜欢
      • 2011-09-09
      • 1970-01-01
      • 2019-10-31
      • 2020-10-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-07-19
      • 2012-12-10
      相关资源
      最近更新 更多