JS DOM: encodeURI, decodeURI
Method encodeURI
encodeURI
is a string property of the
the Global Object.
encodeURI(str)-
Return a new string such that illegal URL characters in str are percent encoded.
This encoding is called percent encoding. It is required for all non-ASCII chars in the URI. (but usually browsers can handle it fine without percent encoding.)
- 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 Unicode: 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 - Each encoded character is changed to the form
Example: Encode Chinese Characters
// encode Chinese characters console.log( encodeURI("δΈζ") === "%E4%B8%AD%E6%96%87" ); // true /* δΈ codepoint 20013 hexadecimal 4e2d utf8 encoding: E4 B8 AD ζ codepoint 25991 hexadecimal 6587 utf8 encoding: E6 96 87 */
Example: Encode a emoji
// encode a emoji console.log( encodeURI("π¦")); // %F0%9F%A6%8B /* π¦ Name: BUTTERFLY ID 129419 HEXD 1F98B UTF8 F0 9F A6 8B UTF16 D83E DD8B */
What characters are changed by encodeURI?
Printable ASCII chars that are changed are:{ } [ ] < > % | \ ^ " `
And all non-ASCII Unicode are also changed.
// unchanged chars of encodeURI const xa = "-_.!~*'()"; console.log(encodeURI(xa) === xa); // true const xb = ";,/?:@&=+$#"; console.log(encodeURI(xb) === xb); // true const xc = "0123456789"; console.log(encodeURI(xc) === xc); // true const xd = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; console.log(encodeURI(xd) === xd); // true const xe = "abcdefghijklmnopqrstuvwxyz"; console.log(encodeURI(xe) === xe); // true