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,0476 gold badges14 silver badges30 bronze badges
asked Dec 21, 2010 at 22:49
4
  • Why don't you check this thing out: lawrence.ecorp.net/inet/samples/regexp-parse.php half way down the page shows you how to extract different parts using javascript regular expressions. Commented Dec 21, 2010 at 22:53
  • That's the relative path Commented Oct 20, 2014 at 10:54
  • 3
    @BenTaliadoros is right - someone should edit the question and description to correctly say "relative path" instead of "absolute path". Commented Sep 17, 2015 at 20:31
  • 1
    @jbyrd stackoverflow.com/review/suggested-edits/10865424 Commented Jan 12, 2016 at 16:35

7 Answers 7

83

Try

window.location.pathname+window.location.search
answered Dec 21, 2010 at 22:55
Sign up to request clarification or add additional context in comments.

Comments

5

The quickest, most complete way:

location.href.replace(/(.+\w\/)(.+)/,"/2ドル");
answered Dec 3, 2013 at 18:29

1 Comment

Not complete, will match full url if there is no path. Returns https://stackoverflow.com/ for example.
4
location.href

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

answered Dec 21, 2010 at 22:54

Comments

4

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

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

answered Aug 25, 2016 at 22:28

Comments

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.

answered Dec 1, 2015 at 12:36

Comments

1

I use this:

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

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

answered Jun 10, 2011 at 21:49

Comments

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 
answered Nov 17, 2015 at 13:19

1 Comment

That's the jQuery way. Why not `location.href' as given in an earlier answer?

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.