Parsing string to add to URL-encoded URL

后端 未结 4 1731
误落风尘
误落风尘 2020-12-08 01:25

Given the string:

\"Hello there world\"

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

\"Hello%20there%20world\"
<         


        
4条回答
  •  自闭症患者
    2020-12-08 02:28

    Ruby's URI is 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:

    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:

    • When to encode space to plus (+) or %20?
    • URL encoding the space character: + or %20?
    • 17.13.4 Form content types from the W3's "Forms in HTML documents" recommendations.

提交回复
热议问题