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: Character, Code Unit, 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 Escape Sequence

String Topic

  1. JS: String Overview
  2. JS: Template String
  3. JS: String Escape Sequence
  4. JS: Unicode Escape Sequence
  5. JS: String Object
  6. JS: String.prototype
  7. JS: String to Number
  8. JS: Encode URL, Escape String
  9. JS: Format Number
  10. JS: JSON
  11. JS: Source Code Encoding
  12. JS: Allowed Characters in Identifier
Liket it? Put $5 at patreon.

Or, Buy JavaScript in Depth

If you have a question, put $5 at patreon and message me.