解析字符串以添加到URL编码的URL

Moh*_*awy 65 ruby ruby-on-rails ruby-on-rails-3

鉴于字符串:

"Hello there world"
Run Code Online (Sandbox Code Playgroud)

如何创建URL编码的字符串,如下所示:

"Hello%20there%20world"
Run Code Online (Sandbox Code Playgroud)

如果字符串也有其他符号,我也想知道该怎么做,比如:

"hello there: world, how are you"
Run Code Online (Sandbox Code Playgroud)

最简单的方法是什么?我打算解析,然后为此构建一些代码.

Ari*_*iao 117

    require 'cgi'

    CGI.escape("Hello world")
    #=> "Hello+world"
Run Code Online (Sandbox Code Playgroud)

  • 如果你还想编码点:`URI.encode('api.example.com',/\W /)` (4认同)
  • 不起作用,例如`URI.encode(“ http://google.com”)=>“ http://google.com”`。更好地使用`CGI.escape`(`“ https%3A%2F%2Fgoogle.com”`) (2认同)

the*_*Man 17

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"
Run Code Online (Sandbox Code Playgroud)

这些例子非常有用:

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"
Run Code Online (Sandbox Code Playgroud)

这些链接也可能有用:

  • 无论何时需要更多的微不足道的逻辑,正确的做法是在控制器中完成所有"计算". (2认同)

Ben*_*min 17

虽然目前的答案表示利用URI.encode自Ruby 1.9.2以来已被弃用和废弃.利用CGI.escape或更好ERB::Util.url_encode.


小智 13

如果有人有兴趣,最新的方法就是在ERB中做:

    <%= u "Hello World !" %>
Run Code Online (Sandbox Code Playgroud)

这将呈现:

您好%20World%20%21

url_encode的缩写

你可以在这里找到文档

  • 使用新方法更新旧答案的奖励积分! (4认同)