javascript:获取网址路径
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 
原文地址: http://stackoverflow.com/questions/4497531/
Warning: these are provided under cc-by-sa 4.0 license.  You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
javascript: get url path
提问by alex
var url = 'http://domain.com/file.php?id=1';
or
或者
var url = 'https://domain.us/file.php?id=1'
or
或者
var url = 'domain.de/file.php?id=1';
or
或者
var url = 'subdomain.domain.com/file.php?id=1'
from either one of these urls I want to get only the path, in the case above:
从这些 url 中的任何一个我只想获取path,在上面的情况下:
var path = '/file.php?id=1';
回答by alex
You coulddo it with regex, but using these native properties are arguably the bestway to do it.
您可以使用正则表达式来实现,但使用这些本机属性可以说是最好的方法。
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
回答by TJ.
In Douglas Crockford's book "JavaScript: The Good Parts", there's a regex for retreiving all url parts. It's on page 66 and you can see it here: http://books.google.ch/books?id=PXa2bby0oQ0C&pg=PA66
在 Douglas Crockford 的“JavaScript: The Good Parts”一书中,有一个用于检索所有 url 部分的正则表达式。它位于第 66 页,您可以在此处查看:http: //books.google.ch/books?id=PXa2bby0oQ0C&pg=PA66
You can copy and paste from here: http://www.coderholic.com/javascript-the-good-parts/
您可以从这里复制和粘贴:http: //www.coderholic.com/javascript-the-good-parts/
回答by stecb
this version is with regex. Try this out:
这个版本是正则表达式。试试这个:
var splittedURL = url.split(/\/+/g);
var path = "/"+splittedURL[splittedURL.length-1];
回答by vonPryz
Use string.lastIndexOf(searchstring, start) instead of a regex. Then check if the index is within bounds and get substring from last slash to end of the string.
使用 string.lastIndexOf(searchstring, start) 而不是正则表达式。然后检查索引是否在边界内并获取从最后一个斜杠到字符串末尾的子字符串。

