DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Escape Single Quotes In Ruby Strings

11.09.2005
| 49418 views |
  • submit to reddit
        
class String
  def escape_single_quotes
    self.gsub(/[']/, '\\\\\'')
  end
end

Useful if you ever get the idea of shoving Ruby strings into JavaScript code.    

Comments

Snippets Manager replied on Thu, 2008/12/11 - 10:21pm

Or just: class String def escape_single_quotes self.gsub(/'/, "\\\\'") end end

Snippets Manager replied on Mon, 2012/05/07 - 1:16pm

In rails you have escape_javascript() http://rails.rubyonrails.com/classes/ActionView/Helpers/JavaScriptHelper.html#M000440