Ruby-on-rails 解析字符串以添加到 URL 编码的 URL

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17375947/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 22:15:49  来源:igfitidea点击:

Parsing string to add to URL-encoded URL

ruby-on-railsrubyruby-on-rails-3

提问by Mohamed El Mahallawy

Given the string:

鉴于字符串:

"Hello there world"

how can I create a URL-encoded string like this:

如何创建这样的 URL 编码字符串:

"Hello%20there%20world"

I would also like to know what to do if the string has other symbols too, like:

我还想知道如果字符串也有其他符号该怎么办,例如:

"hello there: world, how are you"

What would is the easiest way to do so? I was going to parse and then build some code for that.

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

回答by Arie Xiao

In 2019, URI.encode is obsolete and should not be used

2019 年,URI.encode 已过时,不应使用

If you want safely put encrypted string into url without problems with special characters then you could use CGI.escapeor ERB::Util.url_encodefor this purpose.

如果您想安全地将加密字符串放入 url 中而不会出现特殊字符问题,那么您可以使用CGI.escapeERB::Util.url_encode用于此目的。

    require 'cgi'

    CGI.escape("Hello world")
    #=> "Hello+world"

Rails will decode automatically when receiving

Rails 接收时会自动解码

回答by Benjamin

While the current answer says to utilize URI.encodethat has been deprecated and obsolete since Ruby 1.9.2. It is better to utilize CGI.escapeor ERB::Util.url_encode.

虽然当前的答案说使用URI.encode自 Ruby 1.9.2 以来已被弃用和过时。最好使用CGI.escapeERB::Util.url_encode

回答by the Tin Man

Ruby's URIis useful for this. You can build the entire URL programmatically and add the query parameters using that class, and it'll handle the encoding for you:

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"

The examples are useful:

这些例子很有用:

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"

These links might also be useful:

这些链接也可能有用:

回答by oschvr

If anyone is interested, the newest way to do this is doing in ERB:

如果有人感兴趣,最新的方法是在 ERB 中进行:

    <%= u "Hello World !" %>

This will render:

这将呈现:

Hello%20World%20%21

你好%20世界%20%21

uis short for url_encode

uurl_encode 的缩写

You can find the docs here

你可以在这里找到文档