Vanilla JavaScript URL Object


Lets check out the URL Object and SearchParams in JavaScript

27 Jun, 2020 · 2 min 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

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

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

This will return the following object:

hash: "#comments"
host: ""
hostname: ""
href: ""
origin: ""
password: ""
pathname: "/posts/100-articles/"
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

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

JavaScript SearchParams get Specific value

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

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

// true
// false

Getting all SearchParams keys

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

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

Or, perhaps we just want the values:

const values = url.searchParams.values();
for (let 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

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

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!

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

Spread the knowledge with fellow developers on Twitter
Tweet this tip
Powered by Webmentions - Learn more

Read next 📖

Removing all vowels with JavaScript

3 Dec, 2022 · 2 min read

Removing all vowels with JavaScript

10 games to learn JavaScript

2 Dec, 2022 · 3 min read

10 games to learn JavaScript

Join 2099 devs and subscribe to my newsletter