JavaScript encode and escape functions
The encodeURI, encodeURIComponent and escape functions convert special characters in URLs and other URIs by percent encoding the special characters.
- JavaScript: encodeURI function
- The JavaScript
encodeURIfunction is used to encode an entire unencoded URI, such ashttp://authority@www.ExampleOnly.com/my path/my filename.ext?width=100%&my key=my value#fragment-id. It is most useful when the entire URI is hard-coded in the JavaScript code, so that escaping of special characters within any component is already done manually.- encodes all characters that should never be included in a valid URI
- also encodes any percent signs, which is used to encode the unsafe characters
- leaves intact the special characters
#& ./:=?@that act as delimiters within a URI along with$;and all other characters not encoded by encodeURIComponent - uses percent escape encoding of individual UTF-8 octets for non-ASCII characters
- JavaScript: encodeURIComponent function
- The JavaScript
encodeURIComponentfunction can be used to encode individual components of a URI such ashttp,authority,www.ExampleOnly.com,my path,my filename.ext,width,100%,my key,my valueandfragment-idfrom the example used for encodeURI above. This is the function that should be used when the URI is being constructed from variables containing individual components of the URI.- encodes the special characters
#$& ,/:;=?@within a component, in addition to those encoded by the encodeURI function, so they won't be misinterpreted as URI delimiters - leaves intact the alphanumeric characters and special characters
!'()*-._~, which are considered "safe" by RFC 1738, but does encode the characters$ ,anyway - uses percent escape encoding of individual UTF-8 octets for non-ASCII characters
- encodes the special characters
- JavaScript: escape function
-
- The JavaScript escape function should be avoided but may be seen in older code that encodes a space as a plus sign (
+) or that was designed to be compatible with older browsers - should not be used for text that may contain non-ASCII characters because Unicode characters are converted into a non-standard format as
%unnnnrather than using UTF-8 percent escape codes
- The JavaScript escape function should be avoided but may be seen in older code that encodes a space as a plus sign (
JavaScript percent-encoding functions
In all cases, the resulting URI still needs to be converted to valid HTML, by encoding quotes within attributes, ampersands, etc. using HTML character codes.
| Character | encodeURI | HTML | encodeURI |
escape |
|---|---|---|---|---|