如何在JavaScript中解码使用golang的url.QueryEscape编码的数据?

huangapple go评论130阅读模式
英文:

How to decode golang url.QueryEscape data in javascript?

问题

我在JS端有一个经过url.QueryEscape处理的字符串。

url.QueryEscape将空格替换为+号。但在decodeURIComponent中,它们并不会被转换回空格。我应该手动将所有的+号替换为空格吗?正确的解码方法是什么?

英文:

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?

答案1

得分: 2

一种简单的方法是在解码之前将所有的+字符替换为空格。例如:

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

将正确地将字符串解码为"/ +"。请注意,在解码之前执行替换是必要的,因为字符串中可能存在编码的+字符。

英文:

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.

答案2

得分: 0

如果你控制Go端,可以使用url.PathEscape,然后你可以简单地使用decodeURIComponent,不需要任何额外的东西。

英文:

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

huangapple
  • 本文由 发表于 2014年2月1日 21:03:14
  • 转载请务必保留本文链接:https://go.coder-hub.com/21498395.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定