Javascript URL Encoding Tutorial with Examples
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 ~!@#$&*()=:/,;?+
- 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="someone@gmail.com"/>
<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 = "someone@gmail.com";
// ==> someone%40gmail.com
var encodedSearchText = encodeURIComponent(searchText);
console.log(encodedSearchText);
// ==> someone@gmail.com
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>
ECMAScript, Javascript Tutorials
- Introduction to Javascript and ECMAScript
- Quickstart with Javascript
- Alert, Confirm, Prompt Dialog Box in Javascript
- Quickstart with JavaScript
- JavaScript Variables Tutorial with Examples
- Bitwise Operations
- JavaScript Arrays Tutorial with Examples
- JavaScript Loops Tutorial with Examples
- JavaScript Functions Tutorial with Examples
- JavaScript Number Tutorial with Examples
- JavaScript Boolean Tutorial with Examples
- JavaScript Strings Tutorial with Examples
- JavaScript if else Statement Tutorial with Examples
- JavaScript Switch Statement
- JavaScript Error Handling Tutorial with Examples
- JavaScript Date Tutorial with Examples
- JavaScript Modules Tutorial with Examples
- The History of Modules in JavaScript
- JavaScript setTimeout and setInterval Function
- Javascript Form Validation Tutorial with Examples
- JavaScript Web Cookies Tutorial with Examples
- JavaScript void Keyword Tutorial with Examples
- Classes and Objects in JavaScript
- Class and inheritance simulation techniques in JavaScript
- Inheritance and polymorphism in JavaScript
- Undertanding Duck Typing in JavaScript
- JavaScript Symbols Tutorial with Examples
- JavaScript Set Collection Tutorial with Examples
- JavaScript Map Collection Tutorial with Examples
- Undertanding JavaScript Iterables and Iterators
- JavaScript Regular Expressions Tutorial with Examples
- JavaScript Promise, Async/Await Tutorial with Examples
- Javascript Window Tutorial with Examples
- Javascript Console Tutorial with Examples
- Javascript Screen Tutorial with Examples
- Javascript Navigator Tutorial with Examples
- Javascript Geolocation API Tutorial with Examples
- Javascript Location Tutorial with Examples
- Javascript History API Tutorial with Examples
- Javascript Statusbar Tutorial with Examples
- Javascript Locationbar Tutorial with Examples
- Javascript Scrollbars Tutorial with Examples
- Javascript Menubar Tutorial with Examples
- JavaScript JSON Tutorial with Examples
- JavaScript Event Handling Tutorial with Examples
- Javascript MouseEvent Tutorial with Examples
- Javascript WheelEvent Tutorial with Examples
- Javascript KeyboardEvent Tutorial with Examples
- Javascript FocusEvent Tutorial with Examples
- Javascript InputEvent Tutorial with Examples
- Javascript ChangeEvent Tutorial with Examples
- Javascript DragEvent Tutorial with Examples
- Javascript HashChangeEvent Tutorial with Examples
- Javascript URL Encoding Tutorial with Examples
- Javascript FileReader Tutorial with Examples
- Javascript XMLHttpRequest Tutorial with Examples
- Javascript Fetch API Tutorial with Examples
- Parsing XML in Javascript with DOMParser
- Introduction to Javascript HTML5 Canvas API
- Highlighting code with SyntaxHighlighter Javascript library
- What are polyfills in programming science?
Show More