Ruby equivalent to JavaScript’s encodeURIComponent that produces identical output?
13,856
Solution 1
URI.escape(foo, Regexp.new("[^#{URI::PATTERN::UNRESERVED}]"))
found here: How do I raw URL encode/decode in JavaScript and Ruby to get the same values in both?
Solution 2
CGI.escape
should escape correctly, except that spaces are escaped as +
.
Note that URI.escape
has been deprecated in Ruby 1.9.2...
There is a long discussion on ruby-core for those interested.
Solution 3
I think the simplest way is URI.encode_www_form_component
.
Related videos on Youtube
Comments
-
Mo. over 3 years
Hi is there an equivalent ruby method to JavaScript
encodeURIComponent
method? i am using theURI.unescape(str)
but it recognizes the"£"
(afterencodeURIComponent
it becomes"%C2%A3"
) as a"?"
sign. any solution's? thanks -
Mo. almost 14 yearslets say i have a str = "£" i use encodeURIComponent(str) in javascript, but when i use URI.unescape(str) in ruby and that string comes back as a str = "?". so there are differences.
-
Mo. almost 14 yearslets say i have a str = "£" i use encodeURIComponent(str) in javascript, but when i use URI.unescape(str) in ruby and that string comes back as a str = "?". so there are differences
-
Michiel de Mare about 5 years
URI.escape
is obsolete and should not be used. -
Brendon Muir almost 2 years@MichieldeMare, what should be used?