JavaScript: encodeURIComponent

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.

It is like encodeURI, but it also encodes the following chars: {; , / ? : @ & = + $ #} .

console.log(
 encodeURIComponent("http://en.wikipedia.org/wiki/Sylvester–Gallai_theorem")
);
// prints 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
// unchanged chars
const xx = "-_!~*'().0123456789.ABCDEFGHIJKLMNOPQRSTUVWXYZ.abcdefghijklmnopqrstuvwxyz";
console.log(
 encodeURIComponent(xx) === xx
);
// true

// ASCII chars that are changed
console.log(
 encodeURIComponent( " ;,/?:@&=+$#" ) === "%20%3B%2C%2F%3F%3A%40%26%3D%2B%24%23"
);
// true

back to Encode URL, Escape String

JS in Depth
XAH  BUY NOW

JS in Depth

JS Obj Ref

DOM


JS Obj Ref

Static Objects

Primitive Wrapper

Special Objects