JavaScript Encode and Decode URL

JavaScript encode and decode URL/URI; In this tutorial, i am going to show you how to decode and encode the URI/URL in javaScript.

How to Encode and Decode a URL Using JavaScript

Using the following javaScript method, you can encode and decode url or uri in javaScript; as follows:

  • encodeURI() Function
  • decodeURI function()

encodeURI() Function

The encodeURI() function is used to encode a URI.

This function encodes special characters, except: , / ? : @ & = + $ # (Use encodeURIComponent() to encode these characters).

Syntax of encodeURI function()

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 Laratutorials.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 of decodeURI function()

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%Laratutorials.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.

More JavaScript Tutorials

Leave a Comment