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
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
Top comments (0)