encodeURIComponent is a core JavaScript function that escapes special characters in strings so that they can be safely used in URIs as components of query strings or hashes.
encodeURIComponent
is a core JavaScript function, mainly used to escape special characters in strings that are going to be part of URI's query string. For example:
var string = "An `odd' string",
enc_string = encodeURIComponent(string); // === "An%20%60odd'%20string"
The returned string can be safely used in URIs:
// makes an AJAX call to request.php?string=An%20%60odd'%20string
var xhr = new XMLHttpRequest();
xhr.open("GET", "request.php?string=" + enc_string, true);
xhr.onreadystatechange = callback;
xhr.send();
encodeURIComponent
can be used to escape query strings' keys as well.
Differences with escape
and encodeURI
encodeURIComponent
escapes special characters to the format %##
, where ##
is the hexadecimal value of the special character's code, just like escape
and encodeURI
.
But escape
does not escape characters like @
, *
, /
and +
, with the plus commonly interpreted as a space by web servers, so it shouldn't be used when possible. Moreover, escape
encodes Unicode characters as %u####
, while encodeURIComponent
first converts them to the UTF8 character sequence, then it encodes the single bytes. For example:
var unichar = "\u25bc"; // A triangle pointing down
alert(escape(unichar)); // Alerts "%u25BC"
alert(encodeURIComponent(unichar)); // Alerts "%E2%96%BC"
encodeURI
behaves similarly to encodeURIComponent but it doesn't encode some other character, such as /
, &
and =
, as it should be used to escape whole URIs and not just parts of the query string.
Usage to convert a string to UTF-8 encoding
There's a nice trick to convert a string with Unicode characters to their corrisponding UTF-8 encoding:
function toUTF8(string) {
return unescape(encodeURIComponent(string));
}
There's a way to convert it back from UTF-8:
function fromUTF8(string) {
return decodeURIComponent(escape(string));
}