JavaScript encodeURI(), decodeURI() and its components functions

JavascriptWeb DevelopmentObject Oriented Programming

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

The encodeURIComponent() function encodes some parts of the URI by basically encoding the special characters. It also encodes the following characters − (, / ? : @ & = + $ # )

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

The decodeURIComponent() function is used to decode some parts of URI generated by encodeURIComponent().

Following is the code for the encodeURI(),decodeURI() and its component functions −

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(), decodeURI() and its components functions</h1>
<button class="encodeUri">ENCODE URI</button>
<button class="decodeUri">DECODE URI</button>
<button class="encodeUriComponent">ENCODE URI COMPONENT</button>
<button class="decodeUriComponent">DECODE URI COMPONENT</button>
<div class="encode"></div>
<div class="decode"></div>
<h3>
Click on the above buttons to encode or decode URI component
</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);
   });
   let encodeComponent;
   document
   .querySelector(".encodeUriComponent")
   .addEventListener("click", () => {
      encodeComponent = encodeURIComponent(url);
      encodeEle.innerHTML = "Encoded url = " + encodeComponent;
   });
   document
   .querySelector(".decodeUriComponent")
   .addEventListener("click", () => {
      decodeEle.innerHTML =
      "Decoded url = " + decodeURIComponent(encodeComponent);
   });
</script>
</body>
</html>

Output

On clicking the “ENCODE URI” and then “DECODE URI” button −

raja
Updated on 07-May-2020 14:37:11

Advertisements