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.
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.
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.
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.
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With