Vanilla JavaScript URL Object

— 5 minute read

Today we are going to be looking at the JavaScript URL Object. In many occasions you want to read parts of the URL for several reasons, this can be checking if it's a secure connection, if it has a query string or hash. The JavaScript URL Object can help us with these things.

Making a URL Object permalink

To make a URL into a URL Object we use the following code:

var urlInput =
var url = new URL(urlInput);

This will return the following object:

hash: "#comments"
host: ""
hostname: ""
href: ""
origin: ""
password: ""
pathname: "/posts/100-articles-%F0%9F%A5%B3/"
port: ""
protocol: "https:"
search: "?utm_sourche=facebook"
searchParams: URLSearchParams {}
username: ""

As you can see, we can access several different properties.

But what if we want to get the actual value of the utm_source?

JavaScript URL SearchParams permalink

The URL comes with searchParams with a lot of very cool features!

JavaScript SearchParams get Specific value permalink

To get just one specific value we use the following code:

// facebook

Additionally we can even get all if there are more of them:

// ["facebook"]

Check if SearchParams has a specific key permalink

In the above example, we are guessing we have the utm_source, but what if we not sure?

// true
// false

Getting all SearchParams keys permalink

But maybe we want to get all keys to loop over manually?

var keys = url.searchParams.keys();
for (var key of keys) {
// utm_source

Or, perhaps we just want the values:

var values = url.searchParams.values();
for (var value of values) {
// facebook

We can even just loop over both:

url.searchParams.forEach(function(value, key) {
console.log(key, value);
// utm_source facebook

Modifying SearchParams permalink

Another element that comes in handy is the option to modify the SearchParams; we can append/change or delete them.


url.searchParams.append('search', 'JavaScript');
// search: "?utm_source=facebook&search=JavaScript"


url.searchParams.set('search', 'HTML');
// search: "?utm_source=facebook&search=HTML"

Or remove:

// search: "?utm_source=facebook"

Sorting SearchParams permalink

We can even call sort() on the SearchParams to sort them alphabetically.


See these in action on Codepen.

See the Pen Vanilla JavaScript URL Object by Chris Bongers (@rebelchris) on CodePen.

Thank you for reading, and let's connect! permalink

Thank you for reading my blog. Feel free to subscribe to my email newsletter and connect on Facebook or Twitter