When are you supposed to use escape instead of encodeURI / encodeURIComponent?

前端 未结 15 1155
栀梦
栀梦 2020-11-21 07:39

When encoding a query string to be sent to a web server - when do you use escape() and when do you use encodeURI() or encodeURIComponent()

相关标签:
15条回答
  • 2020-11-21 08:05

    Inspired by Johann's table, I've decided to extend the table. I wanted to see which ASCII characters get encoded.

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

    Table shows only the encoded characters. Empty cells mean that the original and the encoded characters are the same.


    Just to be extra, I'm adding another table for urlencode() vs rawurlencode(). The only difference seems to be the encoding of space character.

    <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>
    
    0 讨论(0)
  • 2020-11-21 08:06

    encodeURI() - the escape() function is for javascript escaping, not HTTP.

    0 讨论(0)
  • 2020-11-21 08:07

    Also remember that they all encode different sets of characters, and select the one you need appropriately. encodeURI() encodes fewer characters than encodeURIComponent(), which encodes fewer (and also different, to dannyp's point) characters than escape().

    0 讨论(0)
提交回复
热议问题