A URL is composed of a limited set of characters belonging to the US-ASCII character set. These characters include digits (0-9), letters(A-Z, a-z), and a few special characters ("-"
, "."
, "_"
, "~"
).
URL Encoding of Special Characters
When these characters are not used in their special role inside a URL, they must be encoded.
Character | Code Points (Hexadecimal) | Code Points (Decimal) |
---|---|---|
Dollar (“$”) | 24 | 36 |
Ampersand (“&”) | 26 | 38 |
Plus (“+”) | 2B | 43 |
Comma (“,”) | 2C | 44 |
Forward slash/Virgule (“/”) | 2F | 47 |
Colon (“:”) | 3A | 58 |
Semi-colon (“;”) | 3B | 59 |
Equals (“=”) | 3D | 61 |
Question mark (“?”) | 3F | 63 |
‘At’ symbol (“@”) | 40 | 64 |
URL with special characters example
HTML example code. There are several ways to accomplish the correct URL encoding. Easy way use JavaScript encodeURIComponent() function.
<!DOCTYPE html>
<html>
<body>
<script>
var str = "https://eyehunt.com/[email protected]&password=123";
console.log(encodeURIComponent(str));
</script>
</body>
</html>
Output:
URL encoding to handle special characters in a document URI
URL encoding is often required to convert special characters (such as “/”, “&”, “#”, …), because special characters:
You have three options:
escape()
will not encode:@*/+
encodeURI()
will not encode:~!@#$&*()=:/,;?+'
encodeURIComponent()
will not encode:~!*()'
But in your case, if you want to pass a URL into a GET
parameter of another page, you should use escape
or encodeURIComponent
, but not encodeURI
.
Encode a URL using JavaScript such that it can be put into a GET string?
var myUrl = "http://example.com/index.html?param=1&anotherParam=2";
Check out the built-in function encodeURIComponent(str) and encodeURI(str).
var myOtherUrl = "http://example.com/index.html?url=" + encodeURIComponent(myUrl);
Do comment if you have any doubts or suggestions on this JS char topic.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version