javascript encodeURIComponent and converting spaces to + symbols

前端 未结 2 1717
栀梦
栀梦 2020-12-06 04:47

I would like to encode my URL, but I want to convert spaces to plus symbols.

This is what I attempted to do...

var search = \"Testing this here &         


        
相关标签:
2条回答
  • 2020-12-06 05:20

    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...

    Don't use encodeURIComponent() directly.

    You should use fixedEncodeURIComponent(), as indicated by the MDN Documentation. encodeURIComponent does not encode any of the following: !',()*. You need to use this other function. It will solve not only your space problems, but other character problems.

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

    To quote the MDN Documentation encodeURIComponent()...

    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: fixedEncodeURIComponent().

    0 讨论(0)
  • 2020-12-06 05:36
    encodeURIComponent(search).replace(/%20/g, "+");
    

    What you're doing wrong here is that first you convert spaces to pluses, but then encodeURIComponent converts pluses to "%2B".

    0 讨论(0)
提交回复
热议问题