encodeURIComponent

  • Tags
  • Files

Summary

Encodes a Uniform Resource Identifier (URI) component by replacing each instance of certain characters by one, two, three, or four escape sequences representing the UTF-8 encoding of the character (will only be four escape sequences for characters composed of two "surrogate" characters).

Core Global Method
Implemented in JavaScript ?
ECMAScript Edition ECMAScript 3rd Edition

Syntax

var encoded = encodeURIComponent(str);

Parameters

str
A component of a URI.

Description

encodeURIComponent escapes all characters except the following: alphabetic, decimal digits, - _ . ! ~ * ' ( )

To avoid unexpected requests to the server, you should call encodeURIComponent on any user-entered parameters that will be passed as part of a URI. For example, a user could type "Thyme &time=again" for a variable comment. Not using encodeURIComponent on this variable will give comment=Thyme%20&time=again. Note that the ampersand and the equal sign mark a new key and value pair. So instead of having a POST comment key equal to "Thyme &time=again", you have two POST keys, one equal to "Thyme " and another (time) equal to again.

For application/x-www-form-urlencoded (POST), per http://www.w3.org/TR/html401/interac...m-content-type, spaces are to be replaced by '+', so one may wish to follow a encodeURIComponent replacement with an additional replacement of "%20" with "+".

If one wishes to be more stringent in adhering to RFC 3986 (which reserves !, ', (, ), and *), even though these characters have no formalized URI delimiting uses, the following can be safely used:

function fixedEncodeURIComponent (str) {
  return encodeURIComponent(str).replace(/[!'()]/g, escape).replace(/\*/g, "%2A");
}

See also

Contributors to this page: Np, Hao2lian, axcte, Nils22, Karamochi, evilpie, Brettz9, Potappo, Sheppy, Elchi3, ziyunfei, Nickolay, Waldo, chadaustin, Ptak82, ethertank, rodneyrehm, Mgjbot, kmaglione, Maian, Dria, Nux
Last updated by: chadaustin,
Last reviewed by: chadaustin,