13

whats the simplest way to return the "pathname" from an anchor tags href attribute?

example... say I have:

<a href="http://www.example.com/this/is/my/path.html">Blah</a>

I need to return only this "/this/is/my/path.html" part.

Ideas? I'm using jQuery if it helps..

Thanks!

mike
  • 8,041
  • 19
  • 53
  • 68
  • 2
    See [ How do I parse a URL into hostname and path in javascript? ](http://stackoverflow.com/questions/736513/how-do-i-parse-a-url-into-hostname-and-path-in-javascript). – Matthew Flaschen Sep 27 '10 at 20:42

3 Answers3

30

I think you can use pathname

$('a')[0].pathname;
fehays
  • 3,147
  • 1
  • 24
  • 43
  • Yes, it is as simple as that. http://www.devguru.com/technologies/ecmascript/quickref/location_pathname.html – Samuel Sjöberg Sep 27 '10 at 20:48
  • 7
    Potential warning with this: I'm finding that IE will give you this _without_ a leading slash, while every other browser does? See http://stackoverflow.com/questions/956233/javascript-pathname-ie-quirk and http://blogs.msdn.com/b/ieinternals/archive/2011/02/28/internet-explorer-window-location-pathname-missing-slash-and-host-has-port.aspx – Funka Jan 21 '13 at 21:49
  • @SamuelSjöberg: Broken link. – rvighne Jun 03 '14 at 02:05
6

see working example here.. http://jsfiddle.net/TvNmL/

HTML..

<a id='lnk' href="http://www.example.com/this/is/my/path.html">Blah</a>

javascript...

alert( document.getElementById('lnk').pathname);
Aaron Saunders
  • 33,180
  • 5
  • 60
  • 80
  • See my comment on the other answer on this page regarding irregularity in IE which does not return the leading/initial slash in the path, versus how this works in all other browsers that do. (FF, chrome, safari, and opera all do.) The JsFiddle supplied here is really helpful to test and see this after opening in all your different browsers. – Funka Jan 21 '13 at 22:00
2

I noticed there's still no proper answer that deals with the IE bug that @Funka mentioned, so here's my solution:

HTML

<a href="/foo" id="foo">My link</a>

JS

document.getElementById("foo").getAttribute("href");

results '/foo' on all browsers

shem86
  • 478
  • 4
  • 16