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.

Share:
13,856

Related videos on Youtube

Mo.
Author by

Mo.

Software Engineer

Updated on October 26, 2020

Comments

  • Mo.
    Mo. over 3 years

    Hi is there an equivalent ruby method to JavaScript encodeURIComponent method? i am using the URI.unescape(str) but it recognizes the "£" (after encodeURIComponent it becomes "%C2%A3") as a "?" sign. any solution's? thanks

  • Mo.
    Mo. almost 14 years
    lets 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.
    Mo. almost 14 years
    lets 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
    Michiel de Mare about 5 years
    URI.escape is obsolete and should not be used.
  • Brendon Muir
    Brendon Muir almost 2 years
    @MichieldeMare, what should be used?