简体   繁体   English

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

[英]Get relative path of the page url using javascript

In javascript, how can I get the relative path of the current url? 在javascript中,如何获取当前网址的相对路径?

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

尝试

window.location.pathname+window.location.search
location.href

保存脚本运行的页面的URL。

最快捷,最完整的方式:

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

You can use the below snippet to get the absolute url of any page. 您可以使用以下代码段获取任何页面的绝对网址。

 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 Javascript for more details and multiple ways to achieve the same functionality. Checkout 使用Javascript获取绝对URL以获取更多详细信息以及实现相同功能的多种方法。

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

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

I use this: 我用这个:

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

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

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  

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM