Blog / Quick-fixes

How to encode a URL in JavaScript

How to encode a URL in JavaScript

In this post find the quick and simple solution for how to encode a URL in JavaScript - Quick Fix Series!

Will MaygerWill Mayger
August 11, 2021
Article

In this quick post we will be covering how to encode a URL in JavaScript so you can solve this issue quickly and without having to look any further!

As with all my Quick Fix Series of posts, you will first find the problem described and then the solution just below.

Let’s get stuck in!

The problem - Why do you need to encode a URL in JavaScript

In JavaScript you will occasionally come across a time where you need to modify or create URL parameters.

For the most part you will need to do this if you are formatting some data into a GET request that needs to be applied to the URL parameters.

For example, let’s say you want to make a GET request to some API that accepts a name as one of the parameters, you now need to add that parameter as part of the URL as a GET parameter.

E.G:

https://example.com?name=John

Whilst it might seem like an easy enough concatenation, it is not always that simple, this is where URL encoding comes into play.

You need to make sure that your data has been encoded correctly so that it is URL friendly and can be sent to any system or server without issue.

For example in the example above we sent a name, but that data could have just as easily been an array of names, or a name with a space. What do we do in this situation?

It goes without saying that GET parameters in a URL have their limitations and should be used carefully, especially when considering sensitive information, but for the sake of this post we will assume that all the information needs to be sent via a URL parameter and is safe to do so.

So how can we solve this problem?

How to encode a URL in JavaScript

By far the easiest and best way to encode a URL in JavaScript is to use JavaScript’s URLSearchParams.

The URLSearchParams utility let’s you do just about anything you need when it comes to manipulating URLs in JavaScript, and encoding is one of the things that it does for you.

Let’s take a look at how you might use the URLSearchParams to be able to encode parameters into a URL with JavaScript.

const myUrlParams = new URLSearchParams({ name: "John Snow" })
console.log(myUrlParams.toString()) // name=John+Snow

As you can see for the purpose of how to encode a URL in JavaScript, it is really easy to do, all you need to do is to provide the URLSearchParams constructor with an object of key value pairs where the keys will be the name of the parameter and the values will be converted into the encoded values, ready to be sent in a request.

This can also be done with arrays, like so:

const myUrlParams = new URLSearchParams({
  names: ["John Snow", "Walter White"],
})
console.log(myUrlParams.toString()) // names=John+Snow%2CWalter+White

Now that we have looked at how to encode a set of keys and values passed into the constructor, what about if we wanted to append more values as our application goes on?

Well URLSearchParams comes with a method in which we can do this which is called URLSearchParams.append().

This method will let you append new parameters using a key and a value, similar to how we did so originally by passing in an object with keys and values.

The only difference is that this can be used after the initial constructor has been called and it uses arguments rather than an object, here is how it can be used:

const myUrlParams = new URLSearchParams({
  names: ["John Snow", "Walter White"],
})
console.log(myUrlParams.toString()) // names=John+Snow%2CWalter+White
myUrlParams.append("color", "red")
console.log(myUrlParams.toString()) // names=John+Snow%2CWalter+White&color=red

Lastly, to add this into your complete URL to make a request it is just a case of concatenating it or using a string template.

For good measure it would also be worthwhile adding in a check to make sure you have query parameters before adding in the query string separator (?) to the URL.

For example here is the complete example of encoding a URL in JavaScript:

const myUrl = `https://example.com/api/v2/example`
const myUrlParams = new URLSearchParams({
  names: ["John Snow", "Walter White"],
})

...

let requestURI = `${myUrl}`
if (myUrlParams.entries().length) {
  requestURI = `${requestURI}?${myUrlParams.toString()}`
}
console.log(requestURI) // https://example.com/api/v2/example?names=John+Snow%2CWalter+White

Now there are many other ways to use URLSearchParams such as getting, setting, sorting, deleting and more, but for the basics of how to encode a URL in JavaScript the main thing is to remember to pass any keys and values into URLSearchParams and let it do the encoding for you.

One important thing to remember is that URLSearchParams is not supported in Internet explorer. For most people, in most cases this will be absolutely fine because Internet Explorer is not being supported by many applications and websites any more because very few people are still using it.

If however you do need to support Internet Explorer you will instead want to take a look at encodeURIComponent

Summary

There we have the quick fix to how to encode a URL in JavaScript, if you want more like this be sure to check out some of my other posts!

I hope this post has helped, but before you go I highly recommend that you checkout Pluralsight if you are interested in improving your software engineering skills, such as React, JavaScript, or Typescript (and much more).

Not only does Pluralsight provide you with all the learning material you need but it also let's you learn in a fun, interactive way and gives you the ability to see your current progress and level in a certain skill via their Skill Assessment tool which can help you see what you need to learn next to keep improving!

Learn React, JavaScript and TypeScript

Learn React, JavaScript and TypeScript

Join the platform that top tier companies are using.
Master the skills you need to succeed as a software engineer and take your career to the next level with Pluralsight.

Start here

Some graphics used on this post were made using icons from flaticon.

Latest Posts

Learn React, JavaScript and TypeScript

Learn React, JavaScript and TypeScript

Join the platform that top tier companies are using.
Master the skills you need to succeed as a software engineer and take your career to the next level with Pluralsight.

Start here

Earn more and take your coding career to the next level.

Here you will find my personal recomendations to you, for full disclosure I earn a small commission from some of these links, but I only recommend what I trust and personally use.