encodeURI() and decodeURI() functions in JavaScript.


The encodeURI() function encodes the complete URI including special characters except except (, / ? : @ & = + $ #) characters.

The decodeURI() function decodes the URI generated by the encodeURI() function.

Following is the code for encodeURI() and decodeURI() functions in JavaScript −

Example

 Live Demo

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
   body {
      font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
   }
   .encode,.decode {
      font-size: 18px;
      font-weight: 500;
   }
</style>
</head>
<body>
<h1>encodeURI() and decodeURI() function in JavaScript</h1>
<button class="encodeUri">ENCODE URI</button>
<button class="decodeUri">DECODE URI</button>
<div class="encode"></div>
<div class="decode"></div>
<h3>
Click on the above buttons to encode or decode URI
</h3>
<script>
   let fillEle = document.querySelector(".sample");
   let decodeEle = document.querySelector(".decode");
   let encodeEle = document.querySelector(".encode");
   let url = "https://www.google.com/sample%20link/?img=91gf.jpg&size=451px";
   let encodeUrl;
   document.querySelector(".encodeUri").addEventListener("click", () => {
      encodeUrl = encodeURI(url);
      encodeEle.innerHTML = "Encoded url = " + encodeUrl;
   });
   document.querySelector(".decodeUri").addEventListener("click", () => {
      decodeEle.innerHTML = "Decoded url = " + decodeURI(encodeUrl);
   });
</script>
</body>
</html>

Output

The above code will produce the following output −

On clicking the ‘ENCODE URI’ button −

On clicking the’ ‘DECODE URI’ button −

Updated on: 16-Jul-2020

432 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements