How to parse an URL in JavaScript?

Parsing an URL

It is very simple to parse an URL in javascript by using DOM method rather than Regular expressions. If regular expressions are used then code will be much more complicated. In DOM method just a function call will return the parsed URL

In the following example, initially a function is created and then an anchor tag "a" is created inside it using a DOM method. Later on the provided URL was assigned to the anchor tag using href. Now, when function returns the parts of the URL, it tries to return the parsed parts as shown in the output. Since the url is parsed, JSON.stringify() method is used so as to display the output.


Live Demo

   function URL(url) {
      var urlParser = document.createElement('a');
      urlParser.href = url;
      return {
         protocol: urlParser.protocol,
         hostname: urlParser.hostname,
         port: urlParser.port,
         pathname: urlParser.pathname,
         hash: urlParser.hash