DEV Community

Cover image for How to encode and decode a full URL using JavaScript?
MELVIN GEORGE
MELVIN GEORGE

Posted on • Originally published at melvingeorge.me

How to encode and decode a full URL using JavaScript?

Originally posted here!

To encode and decode a full URL in JavaScript, you can use the encodeURI() and decodeURI() functions respectively available in the global window object.

Consider this URL,

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

If you notice the above URL, you can see the space between the word Hello and World. This URL cannot be sent over the internet safely and needs to be UTF-8 encoded.

Encode URL

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

encodeURI("https://www.google.com/search?q=Hello world");

//Output: https://www.google.com/search?q=Hello%20world
Enter fullscreen mode Exit fullscreen mode

If you see the output above, you can see the space between the two words is now converted to %20, which means we have successfully encoded the URL. Now, this URL can be safely sent over the internet.

Decode URL

To decode the encoded URL, you can use the decodeURI() function like this,

decodeURI("https://www.google.com/search?q=Hello%20world");

// Output: https://www.google.com/search?q=Hello world
Enter fullscreen mode Exit fullscreen mode

Feel free to share if you found this useful 😃.


Top comments (0)