【问题标题】:javascript: get url pathjavascript: 获取 url 路径
【发布时间】:2011-05-28 16:56:56
【问题描述】:
var url = 'http://domain.com/file.php?id=1';

var url = 'https://domain.us/file.php?id=1'

var url = 'domain.de/file.php?id=1';

var url = 'subdomain.domain.com/file.php?id=1'

我想从这些网址中的任何一个获取仅路径,在上述情况下:

var path = '/file.php?id=1';

【问题讨论】:

标签: javascript regex url


【解决方案1】:

可以使用正则表达式来做到这一点,但使用这些原生属性可以说是最好的方法。

var url = 'subdomain.domain.com/file.php?id=1',
    a = document.createElement('a');

a.href = 'http://' + url;
var path = a.pathname + a.search; // /file.php?id=1

See it on jsFiddle.net

【讨论】:

  • 很好的答案 alex,但如果 url 像 'subdomain.domain.com/myfiles/file.php?id=1' 而我只想得到 '/file.php?id =1',我应该使用正则表达式,不是吗?
  • @steweb 这种情况下使用上面的代码获取路径,然后ditch the first segment with a regexpath.replace(/^\/[^\/]+/, '');
  • 相当低估的答案。太棒了。
  • 相当聪明,但只适用于浏览器环境。例如,您无法在 Node.js 中运行它。此外,这一切都归结为字符串操作,因此使用 DOM 元素来做这件事有点尴尬。我不是在投票,只是说;)
  • @LucasPrus 我当然同意你的看法。让浏览器为您进行字符串操作很方便,但幸运的是,在 Node 中,我敢打赌,已经有一堆模块可以做到这一点。
【解决方案2】:

在 Douglas Crockford 的“JavaScript: The Good Parts”一书中,有一个用于检索所有 url 部分的正则表达式。它在第 66 页,你可以在这里看到它:http://books.google.ch/books?id=PXa2bby0oQ0C&pg=PA66

你可以从这里复制粘贴:http://www.coderholic.com/javascript-the-good-parts/

【讨论】:

    【解决方案3】:

    此版本带有正则表达式。试试这个:

    var splittedURL = url.split(/\/+/g);
    var path = "/"+splittedURL[splittedURL.length-1];
    

    【讨论】:

    • 只是一个建议,您可以使用splittedURL.pop() 获取最后一个成员:)
    • 非常感谢 alex,我不知道 pop() - wtf :)
    【解决方案4】:

    使用 string.lastIndexOf(searchstring, start) 而不是正则表达式。然后检查索引是否在范围内并获取从最后一个斜杠到字符串末尾的子字符串。

    【讨论】:

      猜你喜欢
      • 2011-10-20
      • 2011-07-28
      • 2014-06-03
      • 2014-09-15
      • 2019-07-25
      • 2011-05-29
      • 2020-05-14
      • 1970-01-01
      • 2020-12-11
      相关资源
      最近更新 更多