buy prednisone

HTML5 – Parsing URLs in JavaScript without using regex

Quite a while ago, I was asked an interview question: how do you write a function that is capable of parsing URLs such as “https://www.google.com:1234/index.php?mode=searchUser#name=user1&id=135” so that you get back the protocol, host name, port number, and the hash keys and values?

I used regex, and it was an epically long function that I wasn’t confident that it was going to work. I am not going to show you what I wrote at that time, ever.

I am excited to say that with HTML5, it becomes a piece of cake. The anchor element has received tons of new properties that are super useful. See the documentation on HTMLAnchorElement.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
function parseUrl(url) {
   var anchor = document.createElement('a');
   anchor.href = url;

   // certain browsers need the anchor to be in the DOM
   // in order to retrieve properties
   anchor.style.display = 'none'
   document.body.appendChild(anchor);

   return {
      protocol: url.protocol // https:
      hostname: url.hostname // www.google.com
      port: url.port // 1234
      search: url.search.substring(1) // mode=searchUser
      hash: url.hash.substring(1) // name=user1&id=135
   };
}

It’s insanely easy.

You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.
Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>