Better URL handling in modern Javascript

Let it do the work for you 🐶

It's really easy to make mistakes when handling URLs in Javascript. I've made a lot of them myself. And that's why in this post, I'll go over some of the most common mistakes and how to avoid them.

Concatenating search params

Let's take a look at the following example:

This is a very common mistake and easy to miss. (I'm not talking about the typos in the words 👀) If you still can't see the problem, the content query param is added using ? instead of &.

Not encoding search params

Another common mistake is not encoding the search params. You might think that this is not a big deal, but it can lead to some unexpected results. For example, if you have a search param with a space or a special character, it will be encoded as %20 or %3F respectively.

The ultimate solution

Well, these things would work, but there is an easier and better way to handle URLs in Javascript. You can use the URL API to create and modify URLs. It's a lot easier than concatenating strings and it's also safer.

This is a lot easier to read and understand, and it's also safer because you don't have to worry about encoding the search params ✨. I admit, I've not been using this a lot. But I'll definitely start using it from now on. 😁

Avatar of Ismayil Mirzayev with spray paint
September 3, 2023
Views: 89