27

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

Thanks

locoboy
  • 38,002
  • 70
  • 184
  • 260

4 Answers4

49

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

kirilloid
  • 14,011
  • 6
  • 38
  • 52
  • 6
    This should be the accepted answer, as it explains also a bit of differences,.. instead of currently accepted answer saying: Try encodeURIComponent() or escape() – kravemir Dec 14 '19 at 12:12
34

Try encodeURIComponent() or escape()

Dr.Molle
  • 116,463
  • 16
  • 195
  • 201
  • 2
    Note: This does not work for encoding the char '%' itself. Took me along time to find out I had to use "encodeURI" – Robin May 26 '20 at 13:57
4

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

codemirror
  • 3,164
  • 29
  • 42
  • When I use encodeURIComponent for a string with an ampersand, it encodes the ampersand as J&K. This makes it to the server, but decodeURIComponent doesn't recover the string and it remains as J&K – Laura Feb 25 '21 at 15:30
  • @Laura what language is at the server side? – codemirror Feb 26 '21 at 19:05
  • Node.js, so javascript. I figured out what the problem was. For some reason the browser changed the & in the original string to "&" when I accessed it in the client JQuery. So when I encoded it, it encoded "&" to "%XXamp%XX", then the server decoded that to "&". Once I saw that, I changed my process to account for that unexpected conversion and it's working now. – Laura Mar 01 '21 at 16:32
2

Yes, here is

escape('This Guy');