by Sai gowtham

How to parse an URL in JavaScript

Home » javascript » How to parse an URL in JavaScript
How to parse an URL in JavaScript

In this tutorial, we are going to learn about how to parse a URL and access its properties like hostname, port, pathname, search, etc using JavaScript.


In JavaScript, we have URL() constructor which accepts the url as a first argument then it creates and returns the object containing a data related to the provided url.


const google = "";

const url = new URL(google);


// url.hostname = "";
// url.pathname = "/"

parsing-google-url in JavaScript

In the above image, we are seeing the object which is returned by the URL constructor.

Second way

There is also a second way to parse the url by creating an anchor(<a>) element using JavaScript.

const google = "";
const a = document.createElement('a');
a.href= google;

Now, we can access the url properties like this.

console.log(;     // ""
console.log(a.href);     // ""
console.log(a.protocol); // "https:"
console.log(;   // "?q=ss"