对要发送到 Web 服务器的查询字符串进行编码时 - 何时使用 escape() 你什么时候使用 encodeURI() 或者 encodeURIComponent():

使用转义:

escape("% +&=");

或者

使用encodeURI()/encodeURIComponent()

encodeURI("http://www.google.com?var1=value1&var2=value2");

encodeURIComponent("var1=value1&var2=value2");
有帮助吗?

解决方案

逃脱()

不要使用它!escape() 定义在节中 B.2.1.2 逃逸附件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 不允许。

编码URI()

当您需要工作 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

编码 URIComponent()

当您想要对 URL 参数的值进行编码时,请使用encodeURIComponent。

var p1 = encodeURIComponent("http://example.org/?a=12&b=55")

然后您可以创建您需要的 URL:

var url = "http://example.net/?param1=" + p1 + "&param2=99";

您将获得完整的 URL:

http://example.net/?param1=http%3A%2F%2Fexample.org%2F%Ffa%3D12%26b%3D55&param2=99

请注意,encodeURIComponent 不会转义 ' 特点。一个常见的错误是使用它来创建 html 属性,例如 href='MyUrl', ,这可能会遇到注入错误。如果您要从字符串构造 html,请使用 " 代替 ' 对于属性引号,或添加额外的编码层(' 可以编码为%27)。

有关此类编码的更多信息,您可以检查: http://en.wikipedia.org/wiki/Percent-encoding

其他提示

和...之间的不同 encodeURI()encodeURIComponent() 正好是由encodeURIComponent编码的11个字符,但不是由encodeURI编码的:

Table with the ten differences between encodeURI and encodeURIComponent

我很容易生成这个表 控制台表 在 Google Chrome 中使用以下代码:

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 疯狂:查询字符串解析

当我试图理解为什么decodeURIComponent 没有正确解码“+”时,我发现了它。这是摘录:

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 与 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 给出了三个内置函数 -

  1. escape() - 不编码 @*/+此方法在 ECMA 3 之后已被弃用,因此应避免使用。

  2. encodeURI() - 不编码 ~!@#$&*()=:/,;?+'它假定 URI 是完整的 URI,因此不会对 URI 中具有特殊含义的保留字符进行编码。当目的是转换完整的 URL 而不是 URL 的某些特殊片段时,使用此方法。例子 - encodeURI('http://stackoverflow.com');会给 - http://stackoverflow.com

  3. encodeURIComponent() - 不编码 - _ . ! ~ * ' ( )此函数通过将某些字符的每个实例替换为表示字符的 UTF-8 编码的一个、两个、三个或四个转义序列来对统一资源标识符 (URI) 组件进行编码。此方法应用于转换 URL 的组成部分。例如,某些用户输入需要附加示例 - encodeURI('http://stackoverflow.com');将给出 - http%3A%2F%2Fstackoverflow.com

所有这些编码均以 UTF 8 执行,即字符将以 UTF-8 格式转换。

encodeURIComponent 与encodeURI 的不同之处在于它对encodeURI 的保留字符和数字符号# 进行编码

我发现,即使在很好地掌握了各种方法的用途和功能之后,尝试各种方法也是一种很好的健全性检查。

为此我发现 这个网站 对于确认我的怀疑非常有用,我正在做适当的事情。事实证明,它对于解码encodeURIComponent'ed字符串也很有用,因为解释起来相当困难。一个很棒的书签:

http://www.the-art-of-web.com/javascript/escape/

灵感来自 约翰的桌子, ,我决定延长桌子。我想看看哪些 ASCII 字符被编码。

screenshot of console.table

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()rawurlencode(). 。唯一的区别似乎是空格字符的编码。

screenshot of console.table

<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;
};

接受的答案很好。扩展最后一部分:

请注意,encodeURIComponent 不会转义 ' 字符。一个常见的错误是使用它来创建Href ='Myurl'之类的HTML属性,该属性可能会遭受注入错误。如果要从字符串构造HTML,则要么使用“而不是'用于属性报价,要么添加额外的编码层('可以编码为%27)。

如果你想安全一点, 未保留字符的编码百分比 也应该被编码。

您可以使用此方法来转义它们(来源 莫兹拉)

function fixedEncodeURIComponent(str) {
  return encodeURIComponent(str).replace(/[!'()*]/g, function(c) {
    return '%' + c.charCodeAt(0).toString(16);
  });
}

// fixedEncodeURIComponent("'") --> "%27"

@johann-echavarria 答案的现代重写:

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
        )
)

或者,如果您可以使用表格,请替换 console.logconsole.table (为了更漂亮的输出)。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top