为什么不decodeURI(“a + b”)==“a b”? [英] Why doesn't decodeURI("a+b") == "a b"?

查看:103
本文介绍了为什么不decodeURI(“a + b”)==“a b”?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在Ruby中编码URL并使用Javascript对其进行解码。但是,正字符给我带来了奇怪的行为。

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

在Ruby中:

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

到目前为止一切顺利。但是Javascript怎么样?

So far so good. But what about Javascript?

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

基本上我需要一个在Javascript和Ruby中以相同方式编码/解码URL的方法。

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

编辑: decodeURIComponent 不是更好:

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


推荐答案

您可能需要查看 URI.encode URI.decode

require 'uri'

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

我经常使用的替代品 可寻址:: URI

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"

这篇关于为什么不decodeURI(“a + b”)==“a b”?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆