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

Inserts HTML Line Breaks Before All Newlines In A String

08.26.2011
| 7893 views |
  • submit to reddit
        
class String
  def nl2br!
    self.gsub("\n\r","<br />").gsub("\r", "").gsub("\n", "<br />")
  end
end

Example:
text 'line_1
line_2'.nl2br!

Result in HTML:
line_1
<br />
line_2


    

Comments

Snippets Manager replied on Wed, 2009/09/30 - 12:44pm

self.gsub("\r?\n","
").