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

January 10, 2021 - 2 min read

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, world

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

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 = "";

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

const fullURL = urlFirstPart + urlQueryString;

// Output:

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,


//Output: World Hai

Feel free to share if you found this useful 😃.