JS DOM: escape, unescape

By Xah Lee. Date: . Last updated: .

The Escape Method

escape is a string property of the the Global Object.

escape is deprecated.

escape(str)

Return a new string from str with some characters percent encoded.

Forms of the Changed Char

some characters are replaced by this rule:

, where DD is 2 digits of hexadecimal and DDDD is 4 digits of hexadecimal.

The hexadecimal are the code unit of the character. (that is, the first 2 bytes of the character in UTF16)

〔see JS: String Code Unit

Ascii Chars Not Changed

// print out all ASCII chars that escape() does not change

Array.from((Array(128)).keys()).forEach((x) => {
  let xchar = String.fromCharCode(x);
  if (escape(xchar) === xchar) {
    console.log(xchar);
  }
});

// * + - . / 0 1 2 3 4 5 6 7 8 9 @ A B C D E F G H I J K L M N O P Q R S T U V W X Y Z _ a b c d e f g h i j k l m n o p q r s t u v w x y z

All other chars are replaced.

Example. Unchanged Characters

// not changed
console.log(escape("a") === "a");
// true

Example. Changed Characters

console.log( escape (" ") === "%20" );
console.log( escape (",") === "%2C" );

Example. NON-ASCII characters are all changed

console.log( escape ( "α" ) === "%u03B1" );
// true

// α
// Name: GREEK SMALL LETTER ALPHA
// codepoint 945
// codepoint hexadecimal: 3b1

Example. Unicode character with codepoint ≥ 2^16

console.log( escape ( "😂" ) === "%uD83D%uDE02" );
// true

// same as
console.log(
 "%u" +
 // first byte
 "😂". charCodeAt (0) .toString (16) . toUpperCase() +
 "%u" +
 // second byte
 "😂". charCodeAt (1) .toString (16) . toUpperCase()
);

// 😂
// name: FACE WITH TEARS OF JOY
// codepoint decimal: 128514
// codepoint hexadecimal: 1f602
// UTF 16 encoding: D8 3D DE 02

unescape

Use unescape function to decode a string encoded with escape.

JS encode decode URL