Percent encoding javascript
Asked Answered
M

4

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

Marquesan answered 6/2, 2011 at 5:41 Comment(0)
A
34

Try encodeURIComponent() or escape()

Angers answered 6/2, 2011 at 5:44 Comment(1)
Note: This does not work for encoding the char '%' itself. Took me along time to find out I had to use "encodeURI"Jahveh
C
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

Craw answered 6/2, 2011 at 6:1 Comment(1)
This should be the accepted answer, as it explains also a bit of differences,.. instead of currently accepted answer saying: Try encodeURIComponent() or escape()Dotson
A
34

Try encodeURIComponent() or escape()

Angers answered 6/2, 2011 at 5:44 Comment(1)
Note: This does not work for encoding the char '%' itself. Took me along time to find out I had to use "encodeURI"Jahveh
S
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

Subacid answered 29/6, 2017 at 11:55 Comment(3)
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&KIasis
@Iasis what language is at the server side?Subacid
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.Iasis
R
2

Yes, here is

escape('This Guy');
Retrospective answered 6/2, 2011 at 5:46 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.