JS DOM: encodeURIComponent, decodeURIComponent

By Xah Lee. Date: . Last updated: .

encodeURIComponent is a string property of the Global Object.

encodeURIComponent(str)

Return a new string with some character encoded by percent encoding.

similar to encodeURI, but it also encodes the following chars:

; , / ? : @ & = + $ #
console.log(
 encodeURIComponent("http://en.wikipedia.org/wiki/Sylvester–Gallai_theorem")
);
// http%3A%2F%2Fen.wikipedia.org%2Fwiki%2FSylvester%E2%80%93Gallai_theorem

encodeURIComponent is useful if you want to embed a URI as a parameter inside a URI. For example:

http://example.com/url?url=http%3A%2F%2Fen.wikipedia.org%2Fwiki%2FSylvester%E2%80%93Gallai_theorem
// all chars that encodeURIComponent() does not change
console.log((Array.from((Array(128)).keys(), (x) => String.fromCharCode(x)).filter((x) => (encodeURIComponent(x) === x))).join(""));
// !'()*-.0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz~

JavaScript DOM, Get URL, Set URL