Questions tagged [encodeuricomponent]

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));
}
173 questions
0
votes
2 answers

Encode url by Javascript

Friends, I am currently using the below function to encode my data and send them through GET method... I am using ajax to send and php to receive them... function urlencode(a){ a=encodeURIComponent(a); a=a.replace(/\\/g,'%5C'); …
Naz
  • 2,520
  • 2
  • 16
  • 23
0
votes
0 answers

how to get the value of encodeURIComponent

This is a script from my jsignature code i want to get the image data and pass it as a php value to be sent as an pdf email but i don't know how to put the output of the code to be included in the form.