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

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

    I found this article enlightening : Javascript Madness: Query String Parsing

    I found it when I was trying to undersand why decodeURIComponent was not decoding '+' correctly. Here is an extract:

    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!
    

提交回复
热议问题