Parsing string to add url url

Given the line:

"Hello there world" 

how can I create a string encoded in a url:

 "Hello%20there%20world" 

I would also like to know what to do if the string contains other characters, for example:

 "hello there: world, how are you" 

What would be the easiest way to do this? I was going to parse and then create code for this.

+42
ruby ruby-on-rails ruby-on-rails-3
Jun 29 '13 at 1:57
source share
3 answers
 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" 
+77
Jun 29 '13 at 2:12
source share

Ruby URI is useful for this. You can create the entire URL programmatically and add request parameters using this class, and it will 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" 

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 may also be useful:

  • When do I need to encode a space to plus (+) or% 20?
  • Space character URL encoding: + or% 20?
  • 17.13.4 Types of form content from W3 "Forms in HTML documents" guidelines.
+13
Jun 29 '13 at 3:10
source share

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

  <%= u "Hello World !" %> 

This will do:

Hello% 20World% 20% 21

u is not suitable for url_encode

Here you can find documents

+2
May 30 '17 at 10:57 p.m.
source share



All Articles