Get relative path of the page url using javascript

2019-03-17 11:36发布

In javascript, how can I get the relative path of the current url?

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

I want just the /test/this?page=2

7条回答
该账号已被封号
2楼-- · 2019-03-17 11:43

I use this:

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

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

查看更多
【Aperson】
3楼-- · 2019-03-17 11:47

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

Only weird case: http://foo.com/ >> "/"

查看更多
forever°为你锁心
4楼-- · 2019-03-17 11:58

Try

window.location.pathname+window.location.search
查看更多
神经病院院长
5楼-- · 2019-03-17 12:02
location.href

holds the url of the page your script is running in.

查看更多
forever°为你锁心
6楼-- · 2019-03-17 12:02

You should use it the javascript way, to retrieve the complete path including the extensions from the page,

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

So, a path like this, can be retrieved too.

www.google.com/results#tab=2  
查看更多
女痞
7楼-- · 2019-03-17 12:06

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.

查看更多
登录 后发表回答