JS: encodeURI

By Xah Lee. Date: . Last updated: .

encodeURI is a global function object.

〔►see JS: the Global Object

encodeURI(str)

Return a new string such that illegal URL characters in str are percent encoded.

Each encoded character is changed to the form %ab, repeated 1 to 4 times, where a or b is a hexadecimal digit. The 2 digits hexadecimal represents a byte (8 bits). The sequence of bytes together is the character in UTF-8 encoding.

// encode a url that contains space

console.log (
 encodeURI ( "http://example.com/a b.jpg" ) ===
 "http://example.com/a%20b.jpg"
);

// true
// encode Chinese characters
console.log( encodeURI("中国") === "%E4%B8%AD%E5%9B%BD" );
// true

// 中
// codepoint 20013
// hexadecimal 4e2d
// utf8 encoding: E4 B8 AD

// 国
// codepoint 22269
// hexadecimal 56fd
// utf8 encoding: E5 9B BD
// encode a emoji
console.log( encodeURI("😂") === "%F0%9F%98%82" );
// true

// 😂
// name: FACE WITH TEARS OF JOY
// codepoint decimal: 128514
// codepoint hexadecimal: 1f602
// utf8 encoding in hexadecimal : F0 9F 98 82

This encoding is called percent encoding. It is required for all Unicode chars in the URI. (but usually browsers can handle it fine without percent encoding.)

What characters are changed by encodeURI?

Printable ASCII chars that are changed are: {{ } [ ] < > % | \ ^ " `}

And all non-ASCII Unicode are also changed.

The following chars are NOT changed by encodeURI:

// unchanged chars of encodeURI

let xx;

xx = "-_.!~*'()";
console.log ( encodeURI(xx) === xx);
// true

xx = ";,/?:@&=+$#";
console.log ( encodeURI(xx) === xx);
// true

xx = "0123456789";
console.log ( encodeURI(xx) === xx);
// true

xx = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
console.log ( encodeURI(xx) === xx);
// true

xx = "abcdefghijklmnopqrstuvwxyz";
console.log ( encodeURI(xx) === xx);
// true

Reference

ECMAScript® 2016 Language Specification#sec-encodeuri-uri

URL Topic

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

Character Topic

  1. JS: String Code Unit vs Code Point
  2. JS: Convert Character To/From Codepoint
  3. JS: String.fromCodePoint
  4. JS: String.fromCharCode
  5. JS: String.prototype.charAt
  6. JS: String.prototype.charCodeAt
  7. JS: String.prototype.codePointAt
  8. JS: Convert Decimal/Hexadecimal
  9. JS: Unicode Character Escape Sequence

String Topic

  1. JS: Default Charset/Encoding
  2. JS: String Code Unit vs Code Point
  3. JS: Unicode Character Escape Sequence
  4. JS: Allowed Characters in Identifier
  5. HTML: Allowed Characters in id Attribute
  6. HTML: Character Sets and Encoding
  7. HTML/XML Entity List

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

  1. JS: String Object
  2. JS: String.prototype
  3. JS: String Constructor
Like what you read? Buy JavaScript in Depth