javascript tutorial - [5 Solutions] encodeURI / encodeURIComponent - javascript - java script - javascript array
Problem:
When are we supposed to use escape instead of encodeURI / encodeURIComponent?
Solution 1:
Use escape:
escape("% +&=");
click below button to copy the code. By JavaScript tutorial team
OR
use encodeURI() / encodeURIComponent()
encodeURI("http://www.wikitechy.com?var1=value1&var2=value2");
encodeURIComponent("var1=value1&var2=value2");
click below button to copy the code. By JavaScript tutorial team
Solution 2:
escape()
Don't use it, as it has been deprecated since ECMAScript v3.
encodeURI()
Use encodeURI when you want a working URL. Make this call:
encodeURI("http://www.wikitechy.com/a file with spaces.html")
to get:
http://www.wikitechy.com/a%20file%20with%20spaces.html
Don't call encodeURIComponent since it would destroy the URL and return
http%3A%2F%2Fwww.wikitechy.com%2Fa%20file%20with%20spaces.html
click below button to copy the code. By JavaScript tutorial team
encodeURIComponent()
Use encodeURIComponent when you want to encode the value of a URL parameter.
var p1 = encodeURIComponent("http://wikitechy.com/?a=12&b=55")
Then you may create the URL you need:
var url = "http://wikitechy.com/?param1=" + p1 + "¶m2=99";
click below button to copy the code. By JavaScript tutorial team
Solution 3:
var arr = [];
for(var i=0;i<256;i++) {
var char=String.fromCharCode(i);
if(encodeURI(char)!==encodeURIComponent(char)) {
arr.push({
character:char,
encodeURI:encodeURI(char),
encodeURIComponent:encodeURIComponent(char)
});
}
}
console.table(arr);
click below button to copy the code. By JavaScript tutorial team
Solution 4:
String: "A + B"
Expected Query String Encoding: "A+%2B+B"
escape("A + B") = "A%20+%20B" Wrong!
encodeURI("A + B") = "A%20+%20B" Wrong!
encodeURIComponent("A + B") = "A%20%2B%20B" Acceptable, but strange
Encoded String: "A+%2B+B"
Expected Decoding: "A + B"
unescape("A+%2B+B") = "A+++B" Wrong!
decodeURI("A+%2B+B") = "A+++B" Wrong!
decodeURIComponent("A+%2B+B") = "A+++B" Wrong!
click below button to copy the code. By JavaScript tutorial team
Solution 5:
var fileName = 'my file(2).txt';
var header = "Content-Disposition: attachment; filename*=UTF-8''" + encodeRFC5987ValueChars(fileName);
console.log(header);
// logs "Content-Disposition: attachment; filename*=UTF-8''my%20file%282%29.txt"
function encodeRFC5987ValueChars (str) {
return encodeURIComponent(str).
// Note that although RFC3986 reserves "!", RFC5987 does not,
// so we do not need to escape it
replace(/['()]/g, escape). // i.e., %27 %28 %29
replace(/\*/g, '%2A').
// The following are not required for percent-encoding per RFC5987,
// so we can allow for a little better readability over the wire: |`^
replace(/%(?:7C|60|5E)/g, unescape);
}