How to Encode & Decode a URL in JavaScript

Overview

In this tutorial – you will learn how to decode and encode the URI from the given URL in javaScript.

Basically two methods for encode and decode the URL in javascript. javaScript provide encodeURI() for encode a URI and decodeURI() for decode the URI.

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

<!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&amp;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

<!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&amp;hl=test";
      var decode = decodeURI(uri);
      var res = "Encoded URI: " + decode;
      document.getElementById("decode_uri").innerHTML = res;
    }
    </script>

  </body>
</html>

Conclusion

In this tutorial – you have learned how to encode and decode URI using encodeURI() and decodeURI functions of javascript.

Spread the love

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *