The browser has a very efficient URL parser that let you get location.href
, hash
, query
, etc from the current URL. I'd like to use it instead of coding something using regexes.
If you set location.href
or do location.replace(url)
, the page gets redirected in Chrome. I tried to get the prototype of location in this browser, but I can't find location.prototype
. There is a location.__proto__
which is described as the Location
class in the js console, but I can't find a way to instantiate it. Plus, I need a cross browser solution and __proto__
is not available in IE.
If it's not possible, don't give me a regex alternative, just tell me the hard truth, provided you can back it up with evidences.
I wrote a generalized version of the wonderful Mahmoud solution:
It works that way:
The
parseUrl
code is a bit complicated because IE requires the link HTML code to be processed by its HTML parser if you want it to parse the URL. So we create a closure in which we store a<div>
with a<a>
as child (avoid recreating it a each call), and when we need URL parsing, we just take the HTML ofdiv
, and inject it back to itself, forcing IE to parse it.Yes, it's very much possible! If you create a new
a
object, you can use the location fields without redirecting the browser.For instance:
You can now access
.hash
,.pathname
,.host
, and all the other location goodies!