How to Encode and Decode a URL Using JavaScript

how to encode and decode a url using js

In this short tip post, we will learn how to encode a URL using JavaScript native function. Encoding a URL is a very important security aspect.

Table of Contents

Objective

To encode and decode the given URL address.

Approach

We can use JavaScript native encodeURI() and encodeURIComponent() function to encode the URL’s.

encodeURI() cannot encode the ~!@#$&*()=:/,;?+ characters.
encodeURIComponent() encode all the characters except -_.!~*'()

Code

Here is the code.

function encode(url) {
        return {
                uri: encodeURI(url),
                uriFull: encodeURIComponent(url)
        };
}

var encodedURL = encode('https://codeforgeek.com/nodejs');
document.write(JSON.stringify(encodedURL));
document.write('
'
)
document.write(decodeURI(encodedURL.uri));
document.write('
'
)
document.write(decodeURIComponent(encodedURL.uriFull))

Check out the codepen for the live demo.

See the Pen
encode URL javascript
by Shahid Shaikh (@codeforgeek)
on CodePen.


Love JavaScript? Learn more about it here.