2

I like that the current address is nicely split up into sections in window.location, but I would like to be able to take an arbitrary URL and split it up following the exact same logic. I don't know how window.location handles corner cases and rare scenarios, so I would like to avoid doing this manually if possible. Since the browser is already doing this work on the current address I'm hoping it contains a function that can do it to any address.

If there are any nice cross-browser libraries (perhaps jQuery plugins) out there I'd love to hear about them too.

hippietrail
  • 15,848
  • 18
  • 99
  • 158
Hubro
  • 56,214
  • 69
  • 228
  • 381
  • Possible duplicate of [Creating a new location object in javascript](http://stackoverflow.com/questions/3213531/creating-a-new-location-object-in-javascript) – Alex Kalicki Aug 17 '12 at 15:21
  • See also http://stackoverflow.com/questions/470832/getting-an-absolute-url-from-a-relative-one-ie6-issue – Tim Down Aug 17 '12 at 15:25

2 Answers2

4

You could create an a (HTML Anchor Element) element in JavaScript and specify the href attribute. Then you'll be able to call the properties associated with an anchor element, hash, protocol, host, port etc...

https://developer.mozilla.org/en-US/docs/DOM/HTMLAnchorElement

Alex
  • 34,899
  • 5
  • 77
  • 90
  • Example usage: [link](http://james.padolsey.com/javascript/parsing-urls-with-the-dom/) and [related question](http://stackoverflow.com/questions/6736595/how-can-i-turn-a-string-into-a-location-object) – chucksmash Aug 17 '12 at 15:23
  • Handy! Incidentally my use-case is already dealing with the `href` properties of anchor tags so this is a prefect solution :) – Hubro Aug 17 '12 at 15:23
1

Using the info in Xander's answer I've written a small function that parses an URL and returns an object with the desired information. I thought I'd share it here:

function parse_url(url)
{
    var e = document.createElement('a');
    e.href = url;

    return {
        'protocol': e.protocol,
        'hostname': e.hostname,
        'host': e.host,
        'port': e.port,
        'pathname': e.pathname,
        'search': e.search,
        'hash': e.hash
    }
}
Hubro
  • 56,214
  • 69
  • 228
  • 381