How do I parse a URL into hostname and path in javascript?

JavascriptFront End TechnologyObject Oriented Programming

In this article we will discuss how to parse a URL into hostname and path in JavaScript.

Generally, the URL is the address of a given resource on the web. It can be an HTML page, CSS, an image, etc. URL stands for Uniform Resource locater. In this article, we are going to discuss how to parse an URL. URL parsing is a function of traffic management and load-balancing.

Using the constructor URL()

The constructor of the URL class returns an URL object according to the given parameters. Following is the syntax to create an URL object using this −

var parse_url = new URL(url);

Example

The following example demonstrates how to parse an URL in JavaScript. Here, we use the URL() constructor to create an URL object.

<!DOCTYPE html> <html lang="en"> <head> <title>Parsing an URL</title> <p id="hostname"> </p> </head> <body> <script> let given_url = "https://www.tutorialspoint.com/index.html"; let parse_url = new URL(given_url); document.getElementById("hostname").innerHTML = "The host of the URL is: "+parse_url.host; </script> </body> </html>

On executing the above program the text is displayed on the browser.

Using the createElement() method

The JavaScript createElement() method is used to create an HTML element dynamically.

Syntax

Following is the syntax to create a parser using createElement() method.

let parse_url = document.createElememt(“a”);
parse_url.href = given_url;

Example

Here, we use the createElement() method and use it for parsing the given URL.

<!DOCTYPE html> <html lang="en"> <head> <title>Parsing an URL using createElement() method</title> <p id="hostname"> </p> <p id="path"></p> </head> <body> <script> var fun = function(given_url) { var parse_url = document.createElement("a"); parse_url.href = given_url; return parse_url; }; var parse_url = fun("https://www.tutorialspoint.com/index.html"); document.getElementById("hostname").innerHTML = "The host of the URL is: "+parse_url.host; document.getElementById("path").innerHTML = "The pathname of the URL is: "+parse_url.pathname; </script> </body> </html>

On executing the above program the text is displayed on the browser.

raja
Updated on 06-Oct-2022 12:58:38

Advertisements