JS DOM: escape, unescape
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.
some characters are replaced by this rule:
%DD
→ for char with codepoint ≺ 256.%uDDDD
→ for char with codepoint ≥ 256.
, where DD is 2 digits of hexadecimal and DDDD is 4 digits of hexadecimal. (note: a hexadecimal digit is 4 bits. So, 2 hexadecimal digits is 1 byte.)
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〕
The chars that does not change are:
- ASCII letters A to Z and a to z
- digits 0 to 9
- @ (U+40: COMMERCIAL AT)
- * (U+2A: ASTERISK)
- _ (U+5F: LOW LINE)
- + (U+2B: PLUS SIGN)
- - (U+2D: HYPHEN-MINUS)
- . (U+2E: FULL STOP)
- / (U+2F: SOLIDUS)
All other chars are replaced.
Example, not changed characters.
// not changed console.log( escape ("a") === "a" ); // true // not changed console.log( escape (".") === "." ); // true
Example, changed characters.
// changed console.log( escape (" ") === "%20" ); // true // changed console.log( escape (",") === "%2C" ); // true
NON-ASCII characters are all changed.
console.log( escape ( "α" ) === "%u03B1" ); // true // α // Name: GREEK SMALL LETTER ALPHA // codepoint 945 // codepoint hexadecimal: 3b1
Example of 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
Check Which Character Are Changed
// print out all ASCII chars that escape() does not change for (let i = 0; i < 128; i++) { let xchar = String.fromCharCode(i); if (escape(xchar) === xchar) { console.log(i + " " + xchar); } } /* 42 * 43 + 45 - 46 . 47 / 48 0 49 1 50 2 51 3 52 4 53 5 54 6 55 7 56 8 57 9 64 @ 65 A 66 B 67 C 68 D 69 E 70 F 71 G 72 H 73 I 74 J 75 K 76 L 77 M 78 N 79 O 80 P 81 Q 82 R 83 S 84 T 85 U 86 V 87 W 88 X 89 Y 90 Z 95 _ 97 a 98 b 99 c 100 d 101 e 102 f 103 g 104 h 105 i 106 j 107 k 108 l 109 m 110 n 111 o 112 p 113 q 114 r 115 s 116 t 117 u 118 v 119 w 120 x 121 y 122 z */
unescape
Use unescape
function to decode a string encoded with escape
.