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!