【问题标题】:Parsing string to add to URL-encoded URL解析字符串以添加到 URL 编码的 URL
【发布时间】: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


    【解决方案1】:

    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")
    【解决方案2】:

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

    【讨论】:

    • 这个答案是正确的。 CGI.escape("www.foo.com/more/here") 现在可以工作了。关键区别在于斜杠的“/”、分号“:”和数组符号“[”“]”开始编码。谢谢!
    【解决方案3】:

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

        <%= u "Hello World !" %>
    

    这将呈现:

    Hello%20World%20%21

    uurl_encode

    的缩写

    您可以找到文档here

    【讨论】:

      【解决方案4】:

      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"
      

      这些链接也可能有用:

      【讨论】:

      • 如何将 require 'uri' 嵌入到 html.erb 中?还是我必须把它放到控制器中?
      • 正确的做法是,在任何时候需要的不仅仅是琐碎的逻辑,就是在控制器中完成所有“计算”。
      • 酷。我们什么时候应该使用助手?如果我们进行计算,会在帮助器中的许多地方使用并包含在控制器中会怎样。有关系吗?
      猜你喜欢
      • 2016-05-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-01
      • 2020-04-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多