Get relative path of the page url using javascript

隐身守侯 提交于 2019-12-03 04:33:54

Try

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

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

The quickest, most complete way:

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

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.

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

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

I use this:

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

Reference: 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,

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

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

www.google.com/results#tab=2  
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!