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

前端 未结 15 1123
栀梦
栀梦 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:01

    I recommend not to use one of those methods as is. Write your own function which does the right thing.

    MDN has given a good example on url encoding shown below.

    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

提交回复
热议问题