2013-06-29 46 views
44

解析字符串添加到指定字符串URL编码URL

"Hello there world" 

我怎么可以创建一个URL编码的字符串是这样的:

"Hello%20there%20world" 

我也想知道什么如果字符串也有其他符号,例如:

"hello there: world, how are you" 

这样做最简单的方法是什么?我打算解析并为此构建一些代码。

回答

82
require 'uri' 

URI.encode("Hello there world") 
#=> "Hello%20there%20world" 
URI.encode("hello there: world, how are you") 
#=> "hello%20there:%20world,%20how%20are%20you" 

URI.decode("Hello%20there%20world") 
#=> "Hello there world" 
+3

如果你也想编码点:'URI.encode( 'api.example.com',/ \ W /)' – Dennis

14

Ruby的URI对此很有用。您可以通过编程构建整个URL和使用类中添加查询参数,它会为您处理编码:

require 'uri' 

uri = URI.parse('http://foo.com') 
uri.query = URI.encode_www_form(
    's' => "Hello there world" 
) 
uri.to_s # => "http://foo.com?s=Hello+there+world" 

的例子是有用的:

URI.encode_www_form([["q", "ruby"], ["lang", "en"]]) 
#=> "q=ruby&lang=en" 
URI.encode_www_form("q" => "ruby", "lang" => "en") 
#=> "q=ruby&lang=en" 
URI.encode_www_form("q" => ["ruby", "perl"], "lang" => "en") 
#=> "q=ruby&q=perl&lang=en" 
URI.encode_www_form([["q", "ruby"], ["q", "perl"], ["lang", "en"]]) 
#=> "q=ruby&q=perl&lang=en" 

这些链接也可能是有用:

+0

我怎么能嵌入要求 'URI'进入html.erb?或者我必须把它放入控制器? –

+2

任何时候当需要更多的微不足道的逻辑时,正确的做法是在控制器中完成所有“computin”。 –

+0

很酷。我们什么时候应该使用助手?如果我们做了计算,可以在帮助程序的许多地方使用,并且包含在控制器中。有关系吗? –

4

如果有人有兴趣,要做到这一点的最新方法是做在ERB:

<%= u "Hello World !" %> 

这将使:

你好%20World%20%21

u的简称url_encode

您可以找到的文档here

+1

使用新方法更新旧答案的奖励积分! – cabgfx