Javascript 使用javascript获取页面url的相对路径
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4504686/
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
Get relative path of the page url using javascript
提问by raklos
In javascript, how can I get the relative path of the current url?
在javascript中,如何获取当前url的相对路径?
for example http://www.example.com/test/this?page=2
例如 http://www.example.com/test/this?page=2
I want just the /test/this?page=2
我只想要 /test/this?page=2
回答by Dr.Molle
Try
尝试
window.location.pathname+window.location.search
回答by Bernhard Hofmann
location.href
holds the url of the page your script is running in.
保存您的脚本正在运行的页面的 url。
回答by Joe Johnson
The quickest, most complete way:
最快最全的方法:
location.href.replace(/(.+\w\/)(.+)/,"/");
回答by Srinivas Ramakrishna
You can use the below snippet to get the absolute url of any page.
您可以使用以下代码段来获取任何页面的绝对 url。
var getAbsoluteUrl = (function() {
var a;
return function(url) {
if(!a) a = document.createElement('a');
a.href = url;
return a.href;
}
})();
// Sample Result based on the input.
getAbsoluteUrl('/'); //Returns http://stackoverflow.com/
Checkout get absolute URL using Javascriptfor more details and multiple ways to achieve the same functionality.
Checkout使用 Javascript 获取绝对 URL 以获取更多详细信息以及实现相同功能的多种方法。
回答by House3272
location.href.replace(location.origin,'');
location.href.replace(location.origin,'');
Only weird case:
http://foo.com/ >> "/"
唯一奇怪的情况:
http://foo.com/ >> "/"
回答by amypellegrini
I use this:
我用这个:
var absURL = document.URL;
alert(absURL);
回答by Coding active
You should use it the javascript way, to retrieve the complete path including the extensions from the page,
您应该以 javascript 方式使用它,从页面中检索包括扩展名在内的完整路径,
$(location).attr('href');
So, a path like this, can be retrieved too.
因此,也可以检索这样的路径。
www.google.com/results#tab=2