URL-encoding in JavaScript

JavaScript FAQ | JavaScript Strings and RegExp FAQ  

Question: How do I convert a string to URL-encoding?

Answer: You can convert any string to a URL-encoded string (suitable for transmission as a query string or, generally speaking, as part of a URL) using the JavaScript functions escape, encodeURI and encodeURIComponent. Below is a detailed discussion of these functions.

escape   In all browsers that support JavaScript, you can use the escape function. This function works as follows: digits, Latin letters and the characters + - * / . _ @ remain unchanged; all other characters in the original string are replaced by escape-sequences %XX, where XX is the ASCII code of the original character. Example:

escape("It's me!") // result: It%27s%20me%21

For Unicode input strings, the function escape has a more complex behavior. If the input is a Unicode string, then non-ASCII Unicode characters will be converted to the Unicode escape-sequences %uXXXX. For example, escape will encode the capital Cyrillic letter A as %u0410. To decode strings encoded with escape, use the JavaScript function unescape.

encodeURI and encodeURIComponent   In addition to escape, modern browsers support two more functions for URL-encoding: encodeURI and encodeURIComponent. These functions are similar to escape, except that they leave intact some characters that escape encodes (e.g. apostrophe, tilde, parentheses); moreover, encodeURIComponent encodes some characters (+ / @) that escape leaves intact. Unlike escape, the encodeURI and encodeURIComponent functions do not produce %uXXXX for Unicode input; instead, they produce %XX%XX or %XX%XX%XX. For example, encodeURI and encodeURIComponent will encode the capital Cyrillic letter A as %D0%90, and the euro sign (€) as %E2%82%AC. To decode strings encoded with encodeURI and encodeURIComponent, use the JavaScript functions decodeURI and decodeURIComponent, respectively.

The following tables illustrate the differences between escape, encodeURI, and encodeURIComponent.
  • lowerASCII characters
  • upperASCII characters
  • Unicode characters (sample)  
  • Greek Letters
  • Math Symbols
  • Accented Characters
  •  

    Copyright © 1999-2012, JavaScripter.net.