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';

4 Answers4

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

alex
  • 479,566
  • 201
  • 878
  • 984
  • 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? – stecb Dec 21 '10 at 09:10
  • 1
    @steweb In that case, get the path using the code above, and then [ditch the first segment with a regex](http://jsfiddle.net/alexdickson/BdE8G/) `path.replace(/^\/[^\/]+/, '');` – alex Dec 21 '10 at 09:15
  • 2
    Quite underestimated answer. It's brilliant. – netiul Jul 03 '13 at 13:09
  • 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 ;) – Lukasz Prus Nov 11 '13 at 21:39
  • @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. – alex Nov 11 '13 at 22:25
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/

T. Junghans
  • 11,385
  • 7
  • 52
  • 75
2

this version is with regex. Try this out:

var splittedURL = url.split(/\/+/g);
var path = "/"+splittedURL[splittedURL.length-1];
stecb
  • 14,478
  • 2
  • 50
  • 68
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.

vonPryz
  • 22,996
  • 7
  • 54
  • 65