Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parsing string to add to URL-encoded URL

Given the string:

"Hello there world" 

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

"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.

like image 988
Mohamed El Mahallawy Avatar asked Jun 29 '13 01:06

Mohamed El Mahallawy


People also ask

How do I encode a string for URL?

URL encoding replaces unsafe ASCII characters with a "%" followed by two hexadecimal digits. URLs cannot contain spaces. URL encoding normally replaces a space with a plus (+) sign or with %20.

How do you add %20 to a URL?

Instead of encoding a space as “%20,” you can use the plus sign reserved character to represent a space. For example, the URL “http://www.example.com/products%20and%20services.html” can also be encoded as http://www.example.com/products+and+services.html.

Should query parameters be URL encoded?

Why do we need to encode? URLs can only have certain characters from the standard 128 character ASCII set. Reserved characters that do not belong to this set must be encoded. This means that we need to encode these characters when passing them into a URL.


1 Answers

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


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" 
like image 126
Arie Xiao Avatar answered Sep 30 '22 22:09

Arie Xiao