Get relative path of the page url using javascript

后端 未结 7 1112
温柔的废话
温柔的废话 2020-12-29 19:48

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 /te

相关标签:
7条回答
  • 2020-12-29 20:23

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

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

    0 讨论(0)
  • 2020-12-29 20:25
    location.href
    

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

    0 讨论(0)
  • 2020-12-29 20:26

    The quickest, most complete way:

    location.href.replace(/(.+\w\/)(.+)/,"/$2");
    
    0 讨论(0)
  • 2020-12-29 20:30

    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.

    0 讨论(0)
  • I use this:

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

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

    0 讨论(0)
  • 2020-12-29 20:45

    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  
    
    0 讨论(0)
提交回复
热议问题