14
var url = 'http://domain.com/file.php?id=1';

or

var url = 'https://domain.us/file.php?id=1'

or

var url = 'domain.de/file.php?id=1';

or

var url = 'subdomain.domain.com/file.php?id=1'

from either one of these urls I want to get only the path, in the case above:

var path = '/file.php?id=1';
1

4 Answers 4

45

You could do it with regex, but using these native properties are arguably the best way to do it.

var url = 'subdomain.domain.com/file.php?id=1',
    a = document.createElement('a');

a.href = 'http://' + url;
var path = a.pathname + a.search; // /file.php?id=1

See it on jsFiddle.net

Sign up to request clarification or add additional context in comments.

5 Comments

Great answer alex, but what if the url is like 'subdomain.domain.com/myfiles/file.php?id=1' and I just want to get the '/file.php?id=1', I should use regex, no?
@steweb In that case, get the path using the code above, and then ditch the first segment with a regex path.replace(/^\/[^\/]+/, '');
Quite underestimated answer. It's brilliant.
Quite clever but only applies to browser environment. You couldn't run it in Node.js for example. Also it all comes down to string manipulation so employing a DOM element to do it is a bit awkward. I'm not downvoting, just saying ;)
@LucasPrus I certainly agree with you. It's handy to let the browser do the string manipulation for you, but luckily in Node I bet there is a heap of modules that already to this.
7

In Douglas Crockford's book "JavaScript: The Good Parts", there's a regex for retreiving all url parts. It's on page 66 and you can see it here: http://books.google.ch/books?id=PXa2bby0oQ0C&pg=PA66

You can copy and paste from here: http://www.coderholic.com/javascript-the-good-parts/

Comments

2

this version is with regex. Try this out:

var splittedURL = url.split(/\/+/g);
var path = "/"+splittedURL[splittedURL.length-1];

2 Comments

Just a suggestion, you could use splittedURL.pop() to get the last member :)
Thanks a lot alex, I didn't know about pop() - wtf :)
0

Use string.lastIndexOf(searchstring, start) instead of a regex. Then check if the index is within bounds and get substring from last slash to end of the string.

Comments

Your Answer

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