JavaScript URL Objects API

I'm a full-stack developer from South Africa 🇿🇦. I love writing about JavaScript, HTML and CSS.
Search for a command to run...

I'm a full-stack developer from South Africa 🇿🇦. I love writing about JavaScript, HTML and CSS.
No comments yet. Be the first to comment.
Most of you know me for my consistency, a golden arrow in my blog series. I've written 1000 articles in 1008 days! Almost an article a day, and my honeymoon was the only holiday I ever took. I'm super proud of this achievement; it has been a fantasti...

It's not the first time I'll be talking about community. I think it's an essential aspect of any successful tool. This shows in my previous explorations of Astro, Medusa, and now Vendure as well. All these products thrive in a super open, welcoming, ...

The cool part about Vendure is how easy it is to set up and how abstract each layer is. Basically, we get the following elements: External database Server Worker Admin UI Frontend While this is amazing, it also brings a bit of complexity when it co...

The previous article looked at customizing Vendure on a data and process level. In this article, we'll look at customizing emails, as they are often a big part of a webshop system. We'll be looking at two different layers of customization for customi...

Even though Vendure is a pretty significant project out of the box, in some cases, we might want to go in and modify some elements to work to our specific use case. In this article, I'll take a high-level look at some elements we can customize within...

When working in JavaScript, there will come times when you need to either receive or manipulate information from the URL.
Luckily for us, there is the URL API. This is a constructor that we can call on URLs to parse them in an object way.
Let me demonstrate how it works.
const url = new URL(
'https://user:[email protected]:3000/folder/page?param=xyz&new=true#title2'
);
As you can see, I decided to make quite a full URL with many things going on.
If we log this URL, we can quickly see we get a neat object with a lot of information inside it.
# selector and everything behind it #title2daily-dev-tips.com:3000daily-dev-tips.comhttps://user:[email protected]:3000/folder/page?param=xyz&new=true#title2https://daily-dev-tips.com:3000pass/folder/page3000https:?param=xyz&new=trueuserThe exciting part is that the window.location (a Location object) contains all of these plus some additional fields.
When extracting multiple fields, a quick tip is to use object destructuring.
Let's say we want only to get the origin, pathname, and search.
const { origin, pathname, search } = new URL(link);
console.log(origin + pathname + search);
// https://daily-dev-tips.com:3000/folder/page?param=xyz&new=true
We can also take the above parameters and quickly update them.
For instance, what if we want to change the hash location.
url.hash = 'title4';
// https://user:[email protected]:3000/folder/page?param=xyz&new=true#title4
Or if we want to change the pathname.
url.pathname = 'register';
// https://user:[email protected]:3000/register?param=xyz&new=true#title4
After modifying the object, you might want to receive the entire string rather than an object.
You can use the toString() method to achieve that.
url.toString();
Now let's look at the search parameters. These are all items marked after a ? or &.
To get just one specific value we use the following code:
console.log(url.searchParams.get('param'));
// xyz
Additionally we can even get all if there are more of them:
console.log(url.searchParams.getAll('param'));
// ["xyz"]
In the above example, we are guessing we have the param, but what if we are not sure?
console.log(url.searchParams.has('param'));
// true
console.log(url.searchParams.has('fake_param'));
// false
But maybe we want to get all keys to loop over manually?
const keys = url.searchParams.keys();
for (let key of keys) {
console.log(key);
}
// param
// new
Or, perhaps we just want the values:
const values = url.searchParams.values();
for (let value of values) {
console.log(value);
}
// xyz
// true
We can even just loop over both:
url.searchParams.forEach(function (value, key) {
console.log(key, value);
});
// param xyz
// new true
Another element that comes in handy is the option to modify the SearchParams; we can append/change or delete them.
Append:
url.searchParams.append('search', 'JavaScript');
// search: "?param=xyz&new=true&search=JavaScript"
Set:
url.searchParams.set('search', 'HTML');
// search: "?param=xyz&new=true&search=HTML"
Or remove:
url.searchParams.delete('search');
// search: "?param=xyz&new=true"
We can even call sort() on the SearchParams to sort them alphabetically.
url.searchParams.sort();
You can try all of these in the following CodePen.
You can safely use the URL API in all modern browsers.
Thank you for reading my blog. Feel free to subscribe to my email newsletter and connect on Facebook or Twitter