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 =
'https://daily-dev-tips.com/posts/100-articles/?utm_source=facebook#comments';
const url = new URL(urlInput);
console.log(url);
This will return the following object:
hash: "#comments"
host: "daily-dev-tips.com"
hostname: "daily-dev-tips.com"
href: "https://daily-dev-tips.com/posts/100-articles/?utm_source=facebook#comments"
origin: "https://daily-dev-tips.com"
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:
console.log(url.searchParams.get('utm_source'));
// facebook
Additionally we can even get all if there are more of them:
console.log(url.searchParams.getAll('utm_source'));
// ["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?
console.log(url.searchParams.has('utm_source'));
// true
console.log(url.searchParams.has('t_source'));
// 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) {
console.log(key);
}
// utm_source
Or, perhaps we just want the values:
const values = url.searchParams.values();
for (let value of values) {
console.log(value);
}
// 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.
Append:
url.searchParams.append('search', 'JavaScript');
// search: "?utm_source=facebook&search=JavaScript"
Set:
url.searchParams.set('search', 'HTML');
// search: "?utm_source=facebook&search=HTML"
Or remove:
url.searchParams.delete('search');
// search: "?utm_source=facebook"
Sorting SearchParams
We can even call sort()
on the SearchParams
to sort them alphabetically.
url.searchParams.sort();
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