How to encode and decode a part of a URL using JavaScript?

Published January 10, 2021

To encode and decode a part of URL in JavaScript, you can use the encodeURIComponent() and decodeURIComponent() functions respectively available in the global window object.

The encodeURIComponent() is different from the encodeURI() function where the first encodes a full URL including its domain name and protocol whereas the second one ignores the domain and protocol names.

Encode URL

Consider this URL,

https://www.google.com/search?q=Hello world

If you pass this whole URL to the encodeURIComponent() function it encodes the full URL like this,

https%3A%2F%2Fwww.google.com%2Fsearch%3Fq%3DHello%20world.

The encodeURIComponent() doesn't ignore the domain and protocol used and encodes the whole URL itself.

So normally encodeURIComponent() function is used to encode only part of the url whether it may be the query string, hash, etc.

// Url
let urlFirstPart = "https://www.google.com/search?q=";

let urlQueryString = encodeURIComponent("Hello World Hai");

const fullURL = urlFirstPart + urlQueryString;

// Output: https://www.google.com/search?q=Hello%20World%20Hai

As you can see, we are using the encodeURIComponent() to only encode the query string part and then appending that encoded string to get the full url.

Decode URL

This can be done using the decodeURIComponent() function by passing the string into the function like this,

decodeURIComponent("https://www.google.com/search?q=Hello%20World%20Hai");

//Output: https://www.google.com/search?q=Hello World Hai

Feel free to share if you found this useful 😃.


Share on: Facebook Twitter