[编码要发送到Web服务器的查询字符串时-什么时候使用escape()
,什么时候使用encodeURI()
或encodeURIComponent()
:
使用转义:
escape("% +&=");
OR
使用encodeURI()/ encodeURIComponent()
encodeURI("http://www.google.com?var1=value1&var2=value2");
encodeURIComponent("var1=value1&var2=value2");
请勿使用!escape()
在B.2.1.2 escape部分中定义,introduction text of Annex B说:
...本附件中指定的所有语言功能和行为均具有一个或多个不良特征,在没有遗留用法的情况下,将从本规范中删除。 ......编写新的ECMAScript代码时,程序员不应使用或假定这些功能和行为是否存在....
行为:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/escape
特殊字符的编码除外:@ * _ +-。/
代码单元值为0xFF或更小的字符的十六进制形式是两位数字的转义序列:%xx
。
对于具有更大代码单位的字符,使用四位数格式%uxxxx
。查询字符串(在RFC3986中定义)中不允许这样做:
query = *( pchar / "/" / "?" )
pchar = unreserved / pct-encoded / sub-delims / ":" / "@"
unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
pct-encoded = "%" HEXDIG HEXDIG
sub-delims = "!" / "$" / "&" / "'" / "(" / ")"
/ "*" / "+" / "," / ";" / "="
仅当百分号后接两个十六进制数字时才允许使用百分号,不允许百分号后接u
。
想要有效的URL时,请使用encodeURI。拨打电话:
encodeURI("http://www.example.org/a file with spaces.html")
获取:
http://www.example.org/a%20file%20with%20spaces.html
不要调用encodeURIComponent,因为它将破坏URL并返回
http%3A%2F%2Fwww.example.org%2Fa%20file%20with%20spaces.html
要对URL参数的值进行编码时,请使用encodeURIComponent。
var p1 = encodeURIComponent("http://example.org/?a=12&b=55")
然后您可以创建所需的URL:
var url = "http://example.net/?param1=" + p1 + "¶m2=99";
您将获得此完整的URL:
http://example.net/?param1=http%3A%2F%2Fexample.org%2F%Ffa%3D12%26b%3D55¶m2=99
注意,encodeURIComponent不会转义'
字符。一个常见的错误是使用它来创建html属性,例如href='MyUrl'
,这可能会遇到注入错误。如果要从字符串构造html,请使用"
代替'
作为属性引号,或添加额外的编码层('
可以编码为%27)。
有关此类型编码的更多信息,请检查:http://en.wikipedia.org/wiki/Percent-encoding
我发现即使对各种方法的各种用途和功能都有很好的了解,对各种方法进行试验也是一个很好的检查。
为此,我发现this website非常有用,可以证实我怀疑自己在做适当的事情。事实证明,它对于解码encodeURIComponent的字符串很有用,这可能很难解释。很棒的书签:
接受的答案很好。延伸到最后一部分:
注意,encodeURIComponent不会转义'字符。普通的错误是使用它来创建html属性,例如href ='MyUrl',可能会遇到注入错误。如果您正在从构造HTML字符串,或者使用“代替”作为属性引号,或者添加一个额外的编码层(可以编码为%27)。
如果您想安全起见,还应该对percent encoding unreserved characters进行编码。
您可以使用此方法对它们进行转义(源Mozilla)
function fixedEncodeURIComponent(str) {
return encodeURIComponent(str).replace(/[!'()*]/g, function(c) {
return '%' + c.charCodeAt(0).toString(16);
});
}
// fixedEncodeURIComponent("'") --> "%27"
受Johann's table的启发,我决定延长桌位。我想查看对哪些ASCII字符进行编码。
var ascii = " !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~";
var encoded = [];
ascii.split("").forEach(function (char) {
var obj = { char };
if (char != encodeURI(char))
obj.encodeURI = encodeURI(char);
if (char != encodeURIComponent(char))
obj.encodeURIComponent = encodeURIComponent(char);
if (obj.encodeURI || obj.encodeURIComponent)
encoded.push(obj);
});
console.table(encoded);
表仅显示编码的字符。空单元格表示原始字符和编码字符相同。
仅此而已,我为urlencode()
与urlencode()
添加了另一个表格。唯一的区别似乎是空格字符的编码。
rawurlencode()
@ johann-echavarria的答案的现代重写:
<script>
<?php
$ascii = str_split(" !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~", 1);
$encoded = [];
foreach ($ascii as $char) {
$obj = ["char" => $char];
if ($char != urlencode($char))
$obj["urlencode"] = urlencode($char);
if ($char != rawurlencode($char))
$obj["rawurlencode"] = rawurlencode($char);
if (isset($obj["rawurlencode"]) || isset($obj["rawurlencode"]))
$encoded[] = $obj;
}
echo "var encoded = " . json_encode($encoded) . ";";
?>
console.table(encoded);
</script>
或者,如果可以使用表格,则将var escapeURIparam = function(url) {
if (encodeURIComponent) url = encodeURIComponent(url);
else if (encodeURI) url = encodeURI(url);
else url = escape(url);
url = url.replace(/\+/g, '%2B'); // Force the replacement of "+"
return url;
};
替换为console.log(
Array(256)
.fill()
.map((ignore, i) => String.fromCharCode(i))
.filter(
(char) =>
encodeURI(char) !== encodeURIComponent(char)
? {
character: char,
encodeURI: encodeURI(char),
encodeURIComponent: encodeURIComponent(char)
}
: false
)
)
(用于更漂亮的输出)。
encodeURI()
和encodeURIComponent()
之间的差异恰好是由encodeURIComponent编码的11个字符,而不是由encodeURI编码的]:
我使用以下代码在Google Chrome中使用console.table轻松生成了此表:
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);
我发现这篇文章很有启发性:Javascript Madness: Query String Parsing
我在尝试理解时发现了它,以及为什么解码URIComponent无法正确解码'+'。这是摘录:
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!
encodeURIComponent不对-_.!~*'()
进行编码,从而导致将数据发布到xml字符串中的php时出现问题。
例如:<xml><text x="100" y="150" value="It's a value with single quote" />
</xml>
[encodeURI
的一般逃脱%3Cxml%3E%3Ctext%20x=%22100%22%20y=%22150%22%20value=%22It's%20a%20value%20with%20single%20quote%22%20/%3E%20%3C/xml%3E
您可以看到,单引号未编码。为了解决问题,我为编码URL创建了两个函数来解决项目中的问题:
function encodeData(s:String):String{
return encodeURIComponent(s).replace(/\-/g, "%2D").replace(/\_/g, "%5F").replace(/\./g, "%2E").replace(/\!/g, "%21").replace(/\~/g, "%7E").replace(/\*/g, "%2A").replace(/\'/g, "%27").replace(/\(/g, "%28").replace(/\)/g, "%29");
}
用于解码URL:
function decodeData(s:String):String{
try{
return decodeURIComponent(s.replace(/\%2D/g, "-").replace(/\%5F/g, "_").replace(/\%2E/g, ".").replace(/\%21/g, "!").replace(/\%7E/g, "~").replace(/\%2A/g, "*").replace(/\%27/g, "'").replace(/\%28/g, "(").replace(/\%29/g, ")"));
}catch (e:Error) {
}
return "";
}
encodeURI()-escape()函数用于javascript转义,而不是HTTP。
小型比较表Java与JavaScript与PHP。
1. Java URLEncoder.encode (using UTF8 charset)
2. JavaScript encodeURIComponent
3. JavaScript escape
4. PHP urlencode
5. PHP rawurlencode
char JAVA JavaScript --PHP---
[ ] + %20 %20 + %20
[!] %21 ! %21 %21 %21
[*] * * * %2A %2A
['] %27 ' %27 %27 %27
[(] %28 ( %28 %28 %28
[)] %29 ) %29 %29 %29
[;] %3B %3B %3B %3B %3B
[:] %3A %3A %3A %3A %3A
[@] %40 %40 @ %40 %40
[&] %26 %26 %26 %26 %26
[=] %3D %3D %3D %3D %3D
[+] %2B %2B + %2B %2B
[$] %24 %24 %24 %24 %24
[,] %2C %2C %2C %2C %2C
[/] %2F %2F / %2F %2F
[?] %3F %3F %3F %3F %3F
[#] %23 %23 %23 %23 %23
[[] %5B %5B %5B %5B %5B
[]] %5D %5D %5D %5D %5D
----------------------------------------
[~] %7E ~ %7E %7E ~
[-] - - - - -
[_] _ _ _ _ _
[%] %25 %25 %25 %25 %25
[\] %5C %5C %5C %5C %5C
----------------------------------------
char -JAVA- --JavaScript-- -----PHP------
[ä] %C3%A4 %C3%A4 %E4 %C3%A4 %C3%A4
[ф] %D1%84 %D1%84 %u0444 %D1%84 %D1%84
我建议不要按原样使用这些方法之一。编写自己的函数,做正确的事。
MDN在下面显示的URL编码方面给出了很好的例子。
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);
}
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent
还要记住,它们都编码不同的字符集,并适当选择所需的字符集。 encodeURI()编码的字符数少于encodeURIComponent()的编码量,encodeURIComponent()的编码字符数少于escape()编码字符数(也与dannyp相同)。
出于对javascript进行编码的目的,给出了三个内置函数-
escape()
-不编码@*/+
此方法在ECMA 3之后不推荐使用,因此应避免使用。
encodeURI()
-不编码~!@#$&*()=:/,;?+'
它假定URI是完整的URI,因此不对URI中具有特殊含义的保留字符进行编码。当目的是转换完整的URL而不是URL的某些特殊段时,将使用此方法。范例-encodeURI('http://stackoverflow.com');
将给出-http://stackoverflow.com
encodeURIComponent()
-不编码- _ . ! ~ * ' ( )
该函数通过用表示字符的UTF-8编码的一个,两个,三个或四个转义序列替换某些字符的每个实例来对统一资源标识符(URI)组件进行编码。此方法应用于转换URL的组成部分。例如,需要附加一些用户输入范例-encodeURIComponent('http://stackoverflow.com');
将给出-http%3A%2F%2Fstackoverflow.com
所有此编码均以UTF 8执行,即字符将以UTF-8格式转换。
encodeURIComponent与encodeURI的不同之处在于,它编码保留字符和encodeURI的数字符号#