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

前端 未结 15 1121
栀梦
栀梦 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 07:42

    The accepted answer is good. To extend on the last part:

    Note that encodeURIComponent does not escape the ' character. A common bug is to use it to create html attributes such as href='MyUrl', which could suffer an injection bug. If you are constructing html from strings, either use " instead of ' for attribute quotes, or add an extra layer of encoding (' can be encoded as %27).

    If you want to be on the safe side, percent encoding unreserved characters should be encoded as well.

    You can use this method to escape them (source Mozilla)

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

提交回复
热议问题