JavaScript escape vs. encode

 

ATTENTION: THIS PAGE IS Valid HTML 5 AND IS BEST VIEWED WITH HTML 5 - Please upgrade your browser or download one of the HTML 5 compatible browsers such as Mozilla Firefox, Chrome, Opera or IE 9 (March 14, 2011 or later). For more information see HTML 5 browsers.


If you find this helpful, please click the Google +1 Button to the left, if it is white, to make it turn blue or red. Thank you! (It also helps find this page again more easily.)


PDF mobile

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 encodeURI JavaScript function is used to encode an entire unencoded URI, such as http://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 encodeURIComponent JavaScript function can be used to encode individual components of a URI such as http, authority, www.ExampleOnly.com, my path, my filename.ext, width, 100%, my key, my value and fragment-id from 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
JavaScript: escape function
  • escape 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 %unnnn rather than using UTF-8 percent escape codes

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 encodeURIComponent escape

Valid HTML 5