为什么不decodeURI("a + b")=="a b"?

Tom*_*man 21 javascript ruby encode decode urlencode

我正在尝试用Ruby编码URL并用Javascript解码它们.然而,加号角色给了我奇怪的行为.

在Ruby中:

[Dev]> CGI.escape "a b"
=> "a+b"
[Dev]> CGI.unescape "a+b"
=> "a b"
Run Code Online (Sandbox Code Playgroud)

到现在为止还挺好.但是Javascript怎么样?

>>> encodeURI("a b")
"a%20b"
>>> decodeURI("a+b")
"a+b"
Run Code Online (Sandbox Code Playgroud)

基本上我需要一种编码/解码URL的方法,这些方法在Javascript和Ruby中的工作方式相同.

编辑: decodeURIComponent不是更好:

>>> encodeURIComponent("a b")
"a%20b"
>>> decodeURIComponent("a+b")
"a+b"
Run Code Online (Sandbox Code Playgroud)

Mat*_*att 28

+不被视为空间.一种解决方法是替换+,%20然后调用decodeURIComponent

从php.js'采取urldecode:

decodeURIComponent((str+'').replace(/\+/g, '%20'));
Run Code Online (Sandbox Code Playgroud)

  • @VictorYarema我不能告诉你它是怎么来的那样.但问题是查询字符串被认为是`application/x-www-form-urlencoded` - _not_ URIs.并且该MIME有一个规则,即空格必须编码为"+".相关部分:https://www.w3.org/TR/html401/interact/forms.html#h-17.13.4.1 (2认同)

the*_*Man 3

您可能想查看URI.encodeURI.decode

require 'uri'

URI.encode('a + b') # => "a%20+%20b"
URI.decode('a%20+%20b') # => "a + b"
Run Code Online (Sandbox Code Playgroud)

我经常使用的另一种方法是Addressable::URI

require 'addressable/uri'
Addressable::URI.encode('a + b') #=> "a%20+%20b"
Addressable::URI.unencode('a%20+%20b') #=> "a + b"
Run Code Online (Sandbox Code Playgroud)

  • 另请注意,“URI.encode”已弃用:http://stackoverflow.com/questions/2824126/whats-the-difference- Between-uri-escape-and-cgiescape/2832003#2832003 (2认同)