JavaScript URL Objects API

dailydevtips1

Chris Bongers

Posted on July 23, 2022

JavaScript URL Objects API

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.

JavaScript URL API

Let me demonstrate how it works.

const url = new URL(
  'https://user:pass@daily-dev-tips.com:3000/folder/page?param=xyz&new=true#title2'
);
Enter fullscreen mode Exit fullscreen mode

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.

  • hash: The # selector and everything behind it #title2
  • host: The domain and optional post daily-dev-tips.com:3000
  • hostname: The domain alone daily-dev-tips.com
  • href: The full URL we provided https://user:pass@daily-dev-tips.com:3000/folder/page?param=xyz&new=true#title2
  • origin: The complete origin including scheme https://daily-dev-tips.com:3000
  • password: If a password was provided pass
  • pathname: Folder and pages behind the slash /folder/page
  • port: Which port was specified 3000
  • protocol: The protocol that was used https:
  • search: The search params including ? And & ?param=xyz&new=true
  • searchParams: A URLSearchParams object that can be used to get individual search params
  • username: The specified username user

The 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
Enter fullscreen mode Exit fullscreen mode

Modifying URL params

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:pass@daily-dev-tips.com:3000/folder/page?param=xyz&new=true#title4
Enter fullscreen mode Exit fullscreen mode

Or if we want to change the pathname.

url.pathname = 'register';

// https://user:pass@daily-dev-tips.com:3000/register?param=xyz&new=true#title4
Enter fullscreen mode Exit fullscreen mode

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();
Enter fullscreen mode Exit fullscreen mode

JavaScript URL SearchParams

Now let's look at the search parameters. These are all items marked after a ? or &.

JavaScript SearchParams get Specific value

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

console.log(url.searchParams.get('param'));
// xyz
Enter fullscreen mode Exit fullscreen mode

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

console.log(url.searchParams.getAll('param'));
// ["xyz"]
Enter fullscreen mode Exit fullscreen mode

Check if SearchParams has a specific key

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
Enter fullscreen mode Exit fullscreen mode

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);
}
// param
// new
Enter fullscreen mode Exit fullscreen mode

Or, perhaps we just want the values:

const values = url.searchParams.values();
for (let value of values) {
  console.log(value);
}
// xyz
// true
Enter fullscreen mode Exit fullscreen mode

We can even just loop over both:

url.searchParams.forEach(function (value, key) {
  console.log(key, value);
});
// param xyz
// new true
Enter fullscreen mode Exit fullscreen mode

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: "?param=xyz&new=true&search=JavaScript"
Enter fullscreen mode Exit fullscreen mode

Set:

url.searchParams.set('search', 'HTML');
// search: "?param=xyz&new=true&search=HTML"
Enter fullscreen mode Exit fullscreen mode

Or remove:

url.searchParams.delete('search');
// search: "?param=xyz&new=true"
Enter fullscreen mode Exit fullscreen mode

Sorting SearchParams

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

url.searchParams.sort();
Enter fullscreen mode Exit fullscreen mode

You can try all of these in the following CodePen.

Browser Support

You can safely use the URL API in all modern browsers.




Data on support for the url feature across the major browsers from caniuse.com

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

đź’– đź’Ş đź™… đźš©
dailydevtips1
Chris Bongers

Posted on July 23, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related