new URL object in JavaScript

URL is a built-in class in JavaScript which returns the complete URL as an object and you can easily access any part of the provided URL. For example

let url = new URL("");
new URL object in JavaScript

So very small piece of code can return some very important information.

Getting query parameters with Javascript:

You can get query parameters with a new URL object, the example is below:

let url = new URL("");
console.log(url.searchParams) // it will return query parameters of the URL
console.log(url.pathname) will return you path after the base URL

Change URL pathname with URL object:

With a new URL object, You can change the URL path with the URL object. URL object class requires the first parameter to be the path with needs to be replaced within the URL. eg

let url = "";
let new_path = "changethis";
let newUrl = new URL(new_path, url);

With the above code example we will have something like the below:

it is very simple and straight forward and handling URLs in Javascript is easy now.

Complete Detail of what each parameter is returning:

Let me show you a drilled down version of how the complete path will look like:

let URL = new URL(“”)

url.searchparamssearchParams object
url.usernameusername of URL

Which browsers support new URL object:

almost all the major browsers support URL object except for few and by few I mean Internet Explorer do not support JavaScript’s new URL object and safari support is partial.