Javascript URL Encoding Tutorial

View more Tutorials:

1- Javascript URL Encoding

In the article of " HTML URL Encoding", I have explained why you need to encode a URL and table of characters and their encoded values.
In this article, I will show you how to encode and decode a URL using  Javascript.
Let's begin with the question, " How do we do to encode a URL with Javascript?".
Actually, it depends on what you want to do. Javascript provides you with two functions which are encodeURI() and encodeURIComponent(). The difference between these two functions is that which characters will be encoded.
  • The encodeURI () function encodes all the characters except for the [email protected]#$&*()=:/,;?+
  • The encodeURIComponent() function encodes all the characters except for the​​​​​​​ -_.!~*'()
Therefore, the  encodeURI() function will be a good choice if you want to entirely encode a  URL, because the ( http:// ) will not be encoded. Otherwise, you can use the  encodeURIComponent() function if you intend to encode the value of a parameter.
But if you use the encodeURIComponent () function to entirely encode a URL, you will get an unwanted result.
encodeURI("http://example.com/ hey!/")
// http://example.com/%20hey!/


encodeURIComponent("http://www.example.com/ hey!")
//  http%3A%2F%2Fexample.com%2F%20hey!%2F
 
var set1 = ";,/?:@&=+$#";  // Reserved Characters
var set2 = "-_.!~*'()";    // Unreserved Marks
var set3 = "ABC abc 123";  // Alphanumeric Characters + Space

console.log(encodeURI(set1)); // ;,/?:@&=+$#
console.log(encodeURI(set2)); // -_.!~*'()
console.log(encodeURI(set3)); // ABC%20abc%20123 (the space gets encoded as %20)

console.log(encodeURIComponent(set1)); // %3B%2C%2F%3F%3A%40%26%3D%2B%24%23
console.log(encodeURIComponent(set2)); // -_.!~*'()
console.log(encodeURIComponent(set3)); // ABC%20abc%20123 (the space gets encoded as %20)
To decode,  Javascript provides you with two functions, the  decodeURI() and the  decodeURIComponent(). ​​​​​​​Their uses are similar to the two functions, the  encodeURI() and the  encodeURLComponent().

2- encodeURI(), decodeURI()

encodeURI(uri)
The encodeURI(uri) function returns a string which is the encoded result of the uri parameter.
The encodeURI() function encodes all the characters except for the following ones:
A-Z a-z 0-9 ; , / ? : @ & = + $ - _ . ! ~ * ' ( ) #
The encodeURI (uri) function is used to encode a  URL entirely or partially if you want that .
encodeURI-example.html
<!DOCTYPE html>
<html>
<head>
    <title>encodeURI()</title>
    <meta charset="UTF-8">
    <style>input {margin: 10px 0px;}</style>

    <script>
        function doEncodeURI()  {
           var uri = document.getElementById('my-input').value;

           var encodedUri = encodeURI(uri);

           document.getElementById('my-output').value = encodedUri;
        }
    </script>
</head>
<body>
    <h3>encodeURI()</h3>

    Enter URL:
    <input type="text" id="my-input"  style="width:100%;"
        value="http://example.com/my search?value=tom and jerry&maxResults=10"/>

    <button onclick="doEncodeURI()">encodeURI()</button>

    <input type="text" id="my-output"  style="width:100%;" disabled/>
</body>
</html>
Example of using the  decodeURI() function:
decodeURI-example.js
var uri = "http://example.com/my search?value=tom and jerry&maxResults=10";

// ==> http://example.com/my%20search?value=tom%20and%20jerry&maxResults=10
var encodedUri = encodeURI(uri);

console.log(encodeUri);

// ==> http://example.com/my search?value=tom and jerry&maxResults=10
var uri2 = decodeURI(encodedUri);

console.log(uri2);

3- encodeURIComponent(), decodeURIComponent()

encodeURIComponent(uri)
The encodeURIComponent(uri) function returns a string which is the encoded result of the uri parameter.
The  encodeURIComponent() function encodes all the characters except for the following ones:
A-Z a-z 0-9 - _ . ! ~ * ' ( )
 
The  encodeURIComponent(uri) function is usually used to encode the value of the  URL parameter.
encodeURIComponent-example.html
<!DOCTYPE html>
<html>
<head>
    <title>encodeURIComponent()</title>
    <meta charset="UTF-8">
    <style>input {margin: 10px 0px;}</style>

    <script>
        function doEncodeURI()  {
           var searchText = document.getElementById('my-input').value;

           var encodedSearchText = encodeURIComponent(searchText);

            var url = "http://example.com/search?searchText=" + encodedSearchText;

           document.getElementById('my-output').value = url;
        }
    </script>
</head>
<body>
    <h3>encodeURIComponent()</h3>

    Enter Search Text:
    <input type="text" id="my-input"  style="width:100%;"
        value="[email protected]"/>

    <button onclick="doEncodeURI()">Encode</button>

    <input type="text" id="my-output"  style="width:100%;" disabled/>
</body>
</html>
Example of using the decodeURIComponent() function:
decodeURIComponent-example.js
var searchText = "[email protected]";

// ==> someone%40gmail.com
var encodedSearchText = encodeURIComponent(searchText);

console.log(encodedSearchText);

// ==> [email protected]
var text2 = decodeURIComponent(encodedSearchText);

console.log(text2);

4- Encode all characters?

Both the encodeURI() and encodeURIComponent() functions do not encode all the characters. Moreover,  Javascript does not have any other functions to support it; therefore, if you want, you have to write your own function.
encodeURIAll.js
function encodeURIAll(text) {
  return encodeURIComponent(text).replace(/[!'()~*]/g, (c) => {
    return '%' + c.charCodeAt(0).toString(16);
  });
}
 
encodeURIAll-example.html
<!DOCTYPE html>
<html>
<head>
    <title>Encode All Characters</title>
    <meta charset="UTF-8">
    <style>input {margin: 10px 0px;}</style>

    <script src="encodeURIAll.js"></script>

    <script>
        function doEncodeURI()  {
           var text = document.getElementById('my-input').value;

           var encodedUri = encodeURIAll(text);
           console.log(encodedUri)

           document.getElementById('my-output').value = encodedUri;
        }
    </script>
</head>
<body>
    <h3>Encode All Characters</h3>

    Enter Text:
    <input type="text" id="my-input"  style="width:100%;"
        value="abc_.!~*'()"/>

    <button onclick="doEncodeURI()">Encode</button>

    <input type="text" id="my-output"  style="width:100%;" disabled/>
</body>
</html>

View more Tutorials: