Why doesn't decodeURI(“a+b”) == “a b”?

房东的猫 提交于 2019-11-29 06:35:36

问题


I'm trying to encode URLs in Ruby and decode them with Javascript. However, the plus character is giving me weird behavior.

In Ruby:

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

So far so good. But what about Javascript?

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

Basically I need a method of encoding / decoding URLs that works the same way in Javascript and Ruby.

Edit: decodeURIComponent is no better:

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

回答1:


You might want to look at URI.encode and URI.decode:

require 'uri'

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

An alternate, that I use a lot, is Addressable::URI:

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



回答2:


+ is not considered a space. One workaround is to replace + with %20 and then call decodeURIComponent

Taken from php.js' urldecode:

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



回答3:


From MDC decodeURI:

Does not decode escape sequences that could not have been introduced by encodeURI.

From MDC encodeURI:

Note that encodeURI by itself cannot form proper HTTP GET and POST requests, such as for XMLHTTPRequests, because "&", "+", and "=" are not encoded



来源:https://stackoverflow.com/questions/4535288/why-doesnt-decodeuriab-a-b

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!