Percent encoding javascript

后端 未结 4 2005
挽巷
挽巷 2021-02-02 10:55

Is there a javascript function that takes a string and converts it into another string that is percent-encoded? That way something like \"This Guy\" turns into \"This%20Guy\".

相关标签:
4条回答
  • 2021-02-02 11:22

    Yes, here is

    escape('This Guy');
    
    0 讨论(0)
  • 2021-02-02 11:26

    Try this encodeURIComponent()

    var stringToDecode = "J&K";
    
    var encodedString = encodeURIComponent(stringToDecode );
    

    Use decodeURIComponent() to decode it again when needed

    More Info here

    https://en.wikipedia.org/wiki/Percent-encoding#Percent-encoding_reserved_characters

    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent

    0 讨论(0)
  • 2021-02-02 11:27

    Try encodeURIComponent() or escape()

    0 讨论(0)
  • 2021-02-02 11:46

    encodeURI, encodeURIComponent or escape will work the same way for your string, but they differ in details.

    encodeURI is just for escaping URLs
    encodeURIComponent also escapes = and &
    escape works differently with non-ASCII unicode symbols

    encodeURI("Ω") === encodeURIComponent("Ω") === "%CE%A9"
    escape("Ω") === "%u03A9"
    

    if you need to send a string as part of request, use encodeURIComponent

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