javaScript encode and decode URL/URI; In this tutorial, you will learn how to decode and encode the URI/URL from the given URL in javaScript.
How to Encode and Decode a URL Using JavaScript
Basically two methods for encoding and decoding the URL in javascript. javaScript provide encodeURL() for encode a URI and decodeURI() for decode the URL.
encodeURI() Function
The encodeURI() function is used to encode a URI.
This function encodes special characters, except: , / ? : @ & = + $ # (Use encodeURIComponent() to encode these characters).
Syntax
encodeURI(uri)
Example Encode URI JavaScrpt
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<body>
<p>Click the button to Encode a URI</p>
<button onclick="encode()">Click to Encode</button>
<p id="encode_uri"></p>
<script>
function encode() {
var uri = "my tutsmake.com?name=ståleLast&hl=test";
var encode = encodeURI(uri);
var res = "Encoded URI: " + encode;
document.getElementById("encode_uri").innerHTML = res;
}
</script>
</body>
</html>
decodeURI function()
The decodeURI() function is used to decode a URI.
Syntax
decodeURI(uri)
Example Decode URI JavaScrpt
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<body>
<p>Click the button to Decode a URI</p>
<button onclick="decode()">Click to Decode</button>
<p id="decode_uri"></p>
<script>
function decode() {
var uri = " my%20tutsmake.com?name=st%C3%A5leLast&hl=test";
var decode = decodeURI(uri);
var res = "Encoded URI: " + decode;
document.getElementById("decode_uri").innerHTML = res;
}
</script>
</body>
</html>
Conclusion
Encode and Decode URL JavaScript; In this tutorial, you have learned how to encode and decode URI using encodeURI() and decodeURI functions of javascript.