4

I have a string in JS side which is url.QueryEscaped.

Spaces were replaced with + sign by url.QueryEscape. They don't get converted back to space in decodeURIComponent. Should I manually do a string replace all + with space? What is the right way to decode it?

Chakradar Raju
  • 2,691
  • 2
  • 26
  • 42

2 Answers2

2

One simple method is to replace all the + characters with spaces prior to decoding. For example:

decodeURIComponent("%2f+%2b".replace(/\+/g, " "))

will correctly decode the string to "/ +". Note that it is necessary to perform the replacement prior to decoding, since there could be encoded + characters in the string.

James Henstridge
  • 42,244
  • 6
  • 132
  • 114
  • Thanks, thats what I did, but was wondering if I will miss some other encoded characters like space – Chakradar Raju Feb 03 '14 at 13:13
  • 1
    The Go `QueryEscape` function just encodes spaces as plus, and uses percent encoding for other characters not valid in a URL query component. So `replace` and `decodeURIComponent` on the JS side should handle everything. – James Henstridge Feb 03 '14 at 13:27
  • Just a note, the correct way to do a replace all would be to enclose the search string in a RegExp global modifier like so `decodeURIComponent("%2f+%2b".replace(/\+/g, " "))` – Chris Tomich Apr 16 '17 at 15:28
0

If you control Go side, use url.PathEscape and then you can simply use decodeURIComponent without anything extra.

Mitar
  • 6,756
  • 5
  • 54
  • 86