What is the correct way to pull out just the path from a URL using JavaScript?
Example:
I have URL
http://www.somedomain.com/account/search?filter=a#top
but I would just like to get this portion
/account/search
I am using jQuery if there is anything there that can be leveraged.
If this is the current url use window.location.pathname otherwise use this regular expression:
There is a property of the built-in
window.location
object that will provide that for the current window.Update, use the same properties for any URL:
It turns out that this schema is being standardized as an interface called URLUtils, and guess what? Both the existing
window.location
object and anchor elements implement the interface.So you can use the same properties above for any URL — just create an anchor with the URL and access the properties:
[1]: Browser support for the properties that include port is not consistent, See: http://jessepollak.me/chrome-was-wrong-ie-was-right
This works in the latest versions of Chrome and Firefox. I do not have versions of Internet Explorer to test, so please test yourself with the JSFiddle example.
JSFiddle example
There's also a coming
URL
object that will offer this support for URLs themselves, without the anchor element. Looks like no stable browsers support it at this time, but it is said to be coming in Firefox 26. When you think you might have support for it, try it out here.Will give you an array containing all the URL parts, which you can access like a normal array.
Or an ever more elegant solution suggested by @Dylan, with only the path parts: