Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
encodeURIComponent() function in JavaScript
The encodeURIComponent() function accepts a string representing a URI component and encodes it by replacing special characters with percent-encoded sequences. This is essential for safely passing data in URLs.
Syntax
encodeURIComponent(uriComponent)
Parameters
uriComponent: A string to be encoded as a URI component.
Return Value
Returns a new string representing the encoded URI component with special characters replaced by percent-encoded sequences.
Example 1: Basic Usage
<html>
<head>
<title>JavaScript Example</title>
</head>
<body>
<script type="text/javascript">
var url = 'http://www.tutorialspoint.com/';
var result1 = encodeURIComponent(url);
document.write("Original: " + url);
document.write("<br>");
document.write("Encoded: " + result1);
document.write("<br><br>");
var searchQuery = 'JavaScript tutorial & examples';
var result2 = encodeURIComponent(searchQuery);
document.write("Search Query: " + searchQuery);
document.write("<br>");
document.write("URL Safe: " + result2);
</script>
</body>
</html>
Output
Original: http://www.tutorialspoint.com/ Encoded: http%3A%2F%2Fwww.tutorialspoint.com%2F Search Query: JavaScript tutorial & examples URL Safe: JavaScript%20tutorial%20%26%20examples
Example 2: Special Characters
<html>
<head>
<title>Special Characters Example</title>
</head>
<body>
<script type="text/javascript">
var specialChars = '!@#$%^&*()+=[]{}|;":,.<>?/~`';
var encoded = encodeURIComponent(specialChars);
document.write("Original: " + specialChars);
document.write("<br>");
document.write("Encoded: " + encoded);
</script>
</body>
</html>
Output
Original: !@#$%^&*()+=[]{}|;":,.<>?/~`
Encoded: !%40%23%24%25%5E%26*()%2B%3D%5B%5D%7B%7D%7C%3B%22%3A%2C.%3C%3E%3F%2F~%60
Common Use Cases
Query Parameters: Encoding search terms and user input for URL parameters.
API Requests: Ensuring special characters in data don't break URL structure.
Form Data: Safely transmitting form values containing spaces and symbols.
Key Points
-
encodeURIComponent()encodes all characters except:A-Z a-z 0-9 - _ . ! ~ * ' ( ) - Use this for individual URI components, not complete URLs
- Spaces become
%20, ampersands become%26 - Use
decodeURIComponent()to reverse the encoding
Conclusion
The encodeURIComponent() function is essential for safely encoding URI components by converting special characters to percent-encoded sequences. Always use it when building URLs with dynamic data to prevent syntax errors.
