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

我正在尝试在Ruby中编码URL并使用Javascript解码它们。 然而,正字符给我奇怪的行为。

在Ruby中:

[Dev]> CGI.escape "ab" => "a+b" [Dev]> CGI.unescape "a+b" => "ab" 

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

 >>> encodeURI("ab") "a%20b" >>> decodeURI("a+b") "a+b" 

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

编辑: decodeURIComponent不是更好:

 >>> encodeURIComponent("ab") "a%20b" >>> decodeURIComponent("a+b") "a+b" 

您可能想要查看URI.encodeURI.decode

 require 'uri' URI.encode('a + b') # => "a%20+%20b" URI.decode('a%20+%20b') # => "a + b" 

Addressable::URI使用的替代方法是Addressable::URI

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

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

取自php.js’urldecode:

 decodeURIComponent((str+'').replace(/\+/g, '%20')); 

来自MDC decodeURI:

不解码encodeURI无法引入的转义序列。

来自MDC encodeURI:

请注意,encodeURI本身不能形成正确的HTTP GET和POST请求,例如对于XMLHTTPRequests,因为“&”,“+”和“=”不编码