How to parse an URL in JavaScript?

JavascriptObject Oriented ProgrammingFront End Technology

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.

Example

Live Demo

<html>
<body>
<script>
   function URL(url) {
      var urlParser = document.createElement('a');
      urlParser.href = url;
      return {
         protocol: urlParser.protocol,
         host: urlParser.host,
         hostname: urlParser.hostname,
         port: urlParser.port,
         pathname: urlParser.pathname,
         search: urlParser.search,
         hash: urlParser.hash
      };
   }
   document.write(JSON.stringify(URL("https://www.youtube.com/watch?v=tNJJSrfKYwQ")));
</script>
</body>
</html>

Output
{"protocol":"https:","host":"www.youtube.com","hostname":"www.youtube.com","port":"","pathname":"/watch","search":"?v=tNJJSrfKYwQ","hash":""}

raja
Published on 25-Jun-2019 11:02:11
Advertisements