【发布时间】:2013-06-26 21:22:18
【问题描述】:
给定字符串:
"Hello there world"
如何创建这样的 URL 编码字符串:
"Hello%20there%20world"
我也想知道如果字符串还有其他符号怎么办,比如:
"hello there: world, how are you"
最简单的方法是什么?我打算解析然后为此构建一些代码。
【问题讨论】:
标签: ruby-on-rails ruby ruby-on-rails-3
给定字符串:
"Hello there world"
如何创建这样的 URL 编码字符串:
"Hello%20there%20world"
我也想知道如果字符串还有其他符号怎么办,比如:
"hello there: world, how are you"
最简单的方法是什么?我打算解析然后为此构建一些代码。
【问题讨论】:
标签: ruby-on-rails ruby ruby-on-rails-3
2019 年,URI.encode 已过时,不应使用。
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"
【讨论】:
URI.encode('api.example.com', /\W/)
URI.encode("http://google.com") => "http://google.com"。更好地使用CGI.escape ("https%3A%2F%2Fgoogle.com")
虽然当前的答案说使用自 Ruby 1.9.2 以来已被弃用和过时的 URI.encode。最好使用CGI.escape 或ERB::Util.url_encode。
【讨论】:
如果有人感兴趣,最新的方法是在 ERB 中进行:
<%= u "Hello World !" %>
这将呈现:
Hello%20World%20%21
u 是 url_encode
的缩写您可以找到文档here
【讨论】:
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"
这些链接也可能有用:
【讨论】: