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 [email protected]#$&*()=:/,;?+ 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('<br>')
document.write(decodeURI(encodedURL.uri));
document.write('<br>')
document.write(decodeURIComponent(encodedURL.uriFull))
return {
uri: encodeURI(url),
uriFull: encodeURIComponent(url)
};
}
var encodedURL = encode('https://codeforgeek.com/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.