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

<script>
let url = new URL("https://example.com");
console.log(url)
</script>
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:

<script>
let url = new URL("https://example.com/test/path?id=1&status=success");
console.log(url.searchParams) // it will return query parameters of the URL
console.log(url.pathname) will return you path after the base URL
</script>

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

<script>
let url = "https://example.com/path/changeme";
let new_path = "changethis";
let newUrl = new URL(new_path, url);
console.log(newUrl)
</script>

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(“https://example.com/path?id=1&status=success”)

KEYVALUE
url.protocolhttps://
url.hostexample.com
url.hostnameexample.com
url.hrefhttps://example.com/path?id=1&status=success
url.originhttps://example.com
url.passwordpassword
url.pathname/path
url.search?id=1&status=success
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.