使用javascript获取页面URL的相对路径

时间:2010-12-21 22:49:18

标签: javascript url absolute-path

在javascript中,如何获取当前网址的相对路径?

例如http://www.example.com/test/this?page=2

我只想要/test/this?page=2

7 个答案:

答案 0 :(得分:47)

尝试

window.location.pathname+window.location.search

答案 1 :(得分:4)

location.href

保存您的脚本正在运行的页面的URL。

答案 2 :(得分:3)

您可以使用以下代码段获取任何页面的绝对网址。

 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/

结帐get absolute URL using Javascript了解更多详情和实现相同功能的多种方法。

答案 3 :(得分:2)

最快,最完整的方式:

location.href.replace(/(.+\w\/)(.+)/,"/$2");

答案 4 :(得分:2)

location.href.replace(location.origin,'');

只有奇怪的情况: http://foo.com/ >> "/"

答案 5 :(得分:0)

我用这个:

var absURL = document.URL;
alert(absURL);

参考:http://www.w3schools.com/jsref/prop_doc_url.asp

答案 6 :(得分:-1)

您应该以javascript方式使用它,从页面中检索包括扩展名在内的完整路径

$(location).attr('href'); 

因此,也可以检索这样的路径。

www.google.com/results#tab=2