JS: escape

By Xah Lee. Date: . Last updated: .

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:

, 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:

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 ch = String.fromCharCode(i);
    if ( escape(ch) === ch ) {
        console.log( i + " " + ch);
    }
}

// 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().

back to Encode URL, Escape String

BUY ΣJS JavaScript in Depth