JavaScript: escape

By Xah Lee. Date: .

escape is a global function object.

〔►see JavaScript: the Global Object

escape(str)

Return a new string from str. The chars that does not change are: ASCII letters, digits, and the { @ * _ + - . /}. All other chars are replaced by the form %dd or %udddd, where dd is 2 digits of hexadecimal and dddd is 4 digits of hexadecimal. They are the Unicode code point of the char.

〔►see Unicode Basics: What's Character Set, Character Encoding, UTF-8?

escape(…) is deprecated.

Use unescape(…) function to decode a string encoded with escape(…).

console.log(
    escape("http://en.wikipedia.org/wiki/Sylvester–Gallai_theorem")
);
// prints http%3A//en.wikipedia.org/wiki/Sylvester%u2013Gallai_theorem
// -*- coding: utf-8 -*-
// escape() examples

// unchanged
var xx = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
console.log(escape(xx) === xx); // true

// double quote and backslash
console.log(escape(
"\"\\"
));
// %22%5C

console.log(escape(
"!#$%&'()*+,-./:;<=>?@[]^_`{|}~"
));
// %21%23%24%25%26%27%28%29*+%2C-./%3A%3B%3C%3D%3E%3F@%5B%5D%5E_%60%7B%7C%7D%7E

// space, tab, return
console.log(escape(
" \n\t"
));
// %20%0A%09

// unicode
console.log(escape(
"αβγ♥"
));
// %u03B1%u03B2%u03B3%u2665
// print out all ASCII chars that escape() encodes

for (var i = 0; i < 128; i++) {
    var char = String.fromCharCode(i);
    if ( escape(char) !== char ) {
        console.log(  i + " " + char);
    }
}

// 0 &#0;
// 1 &#1;
// 2 &#2;
// 3 &#3;
// 4 &#4;
// 5 &#5;
// 6 &#6;
// 7 &#7;
// 8 &#8;
// 9
// 10

// 11 &#11;
// 12 &#12;
// 13

// 14 &#14;
// 15 &#15;
// 16 &#16;
// 17 &#17;
// 18 &#18;
// 19 &#19;
// 20 &#20;
// 21 &#21;
// 22 &#22;
// 23 &#23;
// 24 &#24;
// 25 &#25;
// 26 &#26;
// 27 &#27;
// 28 &#28;
// 29 &#29;
// 30 &#30;
// 31 &#31;
// 32
// 33 !
// 34 "
// 35 #
// 36 $
// 37 %
// 38 &
// 39 '
// 40 (
// 41 )
// 44 ,
// 58 :
// 59 ;
// 60 <
// 61 =
// 62 >
// 63 ?
// 91 [
// 92 \
// 93 ]
// 94 ^
// 96 `
// 123 {
// 124 |
// 125 }
// 126 ~
// 127 &#127;

Reference

ECMAScript® 2016 Language Specification#sec-additional-properties-of-the-global-object

URL Topic

  1. JavaScript: encodeURI
  2. JavaScript: encodeURIComponent
  3. JavaScript: escape
  4. JavaScript: Get URL (window.location)

String Topic

  1. JavaScript: Default Charset/Encoding
  2. JavaScript: String is 16-Bit Unit Sequence
  3. JavaScript: Unicode Character Escape Sequence
  4. JavaScript: Allowed Characters in Identifier
  5. HTML: Allowed Characters in id Attribute
  6. HTML: Character Sets and Encoding
  7. HTML XML Entities

  1. JavaScript: Template String
  2. JavaScript: Convert String to Number
  3. JavaScript Encode URL, Escape String
  4. JavaScript: Format Number
  5. JavaScript: JSON Object

  1. JavaScript: String Object
  2. JavaScript: String.prototype
  3. JavaScript: String Constructor
Like what you read? Buy JavaScript in Depth
or, buy a new keyboard, see Keyboard Reviews.