Javascript encodeURIComponent doesn't encode single quotes

后端 未结 6 1488
刺人心
刺人心 2021-02-01 03:39

Try it out:

encodeURIComponent(\"\'@#$%^&\");

If you try this out you will see all the special characters are encoded except for the single

6条回答
  •  耶瑟儿~
    2021-02-01 04:09

    Just try encodeURI() and encodeURIComponent() yourself...

    console.log(encodeURIComponent('@#$%^&*'));

    Input: @#$%^&*. Output: %40%23%24%25%5E%26*. So, wait, what happened to *? Why wasn't this converted? TLDR: You actually want fixedEncodeURIComponent() and fixedEncodeURI(). Long-story...

    encodeURIComponent() : Do not use. Use fixedEncodeURIComponent(), as defined and explained by the MDN encodeURIComponent() Documentation, emphasis mine...

    To be more stringent in adhering to RFC 3986 (which reserves !, ', (, ), and *), even though these characters have no formalized URI delimiting uses, the following can be safely used:

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

    While we're on the topic, also don't use encodeURI(). MDN also has their own rewrite of it, as defined by the MDN encodeURI() Documentation. To quote their explanation...

    If one wishes to follow the more recent RFC3986 for URLs, which makes square brackets reserved (for IPv6) and thus not encoded when forming something which could be part of a URL (such as a host), the following code snippet may help:

    function fixedEncodeURI(str) { return encodeURI(str).replace(/%5B/g, '[').replace(/%5D/g, ']'); }

提交回复
热议问题