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

前端 未结 15 1183
栀梦
栀梦 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.

    
    

提交回复
热议问题