38

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

House3272
  • 1,007
  • 5
  • 14
  • 29
raklos
  • 28,027
  • 60
  • 183
  • 301
  • That's the relative path – Ben Taliadoros Oct 20 '14 at 10:54
  • 3
    @BenTaliadoros is right - someone should edit the question and description to correctly say "relative path" instead of "absolute path". – jbyrd Sep 17 '15 at 20:31
  • 1
    @jbyrd https://stackoverflow.com/review/suggested-edits/10865424 –  Jan 12 '16 at 16:35
  • Why don't you check this thing out: http://lawrence.ecorp.net/inet/samples/regexp-parse.php half way down the page shows you how to extract different parts using javascript regular expressions. – JohnMerlino Dec 21 '10 at 22:53

7 Answers7

83

Try

window.location.pathname+window.location.search
Dr.Molle
  • 116,463
  • 16
  • 195
  • 201
5

The quickest, most complete way:

location.href.replace(/(.+\w\/)(.+)/,"/$2");
Joe Johnson
  • 1,814
  • 16
  • 20
  • Not complete, will match full url if there is no path. Returns `https://stackoverflow.com/` for example. – House3272 Aug 25 '16 at 22:15
4

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

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

House3272
  • 1,007
  • 5
  • 14
  • 29
4
location.href

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

Bernhard Hofmann
  • 10,321
  • 12
  • 59
  • 78
3

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.

Srinivas Ramakrishna
  • 1,294
  • 13
  • 21
1

I use this:

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

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

amypellegrini
  • 1,026
  • 9
  • 13
0

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  
Coding active
  • 1,620
  • 3
  • 23
  • 40