Have you ever needed to parse a URL using regular expressions? It’s not easy to write regular expressions (for a lot of people, including myself) and it’s even tougher to test to see if that regular expression is reliable across every situation. You could, of course, just copy and paste a regular expression (or function or library) that someone else developed and use that, but I propose that there is a simpler and more concise way of parsing URLs that doesn’t require any regular expressions.
This method – originally posted on Github by John Long, though probably not originally discovered by him – uses native parsing abilities built into the DOM to give you simple access to the parts of a URL simply by querying properties of an anchor element. Check it out:
This code is pulled directly from the Gist that John Long posted at the above link. I haven’t seen any statements about which browsers this works with, but I assume that, at a minimum, it works with all modern browsers. If you don’t trust it you can either test it yourself, or use a library such as URI.js.
One of the coolest things about this method is that you can enter a partial/relative URL into the
href property and the browser will make it a full URL, just like it translates partial URLs on real HTML links into full URLs. For example, try this using your browsers console on this page:
You could also just use an empty string for the
href and it would give you your current URL (not including the hash, though), but this is a waste because
window.location has the exact same properties, so you don’t even need to create an anchor element for that.
In all of these examples, you still need to parse the query string, but at least you’ve got it pulled out of the URL.
I found a post stating that this does not work in IE6 because the
href property isn’t parsed into a full URL unless it is parsed by the HTML parser. There is a simple workaround that forces the HTML parser to go over it though: