how to encode and decode a url using js

How to Encode and Decode a URL Using JavaScript

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.

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/category/nodejs');
document.write(JSON.stringify(encodedURL));
document.write('<br>')
document.write(decodeURI(encodedURL.uri));
document.write('<br>')
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.

Shahid

Founder of Codeforgeek. Technologist. Published Author. Engineer. Content Creator. Teaching Everything I learn!

Related Posts

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.