converting all newline characters to br tag
August 7, 2006
I was surprised as there is no function in ruby to convert all newline characters to <br>.
Here is a php nl2br equivalent method to convert all newline characters (\n) to break tag (<br>) in a string.
def nl2br(s)
s.gsub(/\n/, '<br>')
end
Entry Filed under: Ruby, RubyonRails, rails. .
12 Comments Add your own
Leave a Comment
Some HTML allowed:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <pre> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>
Trackback this post | Subscribe to the comments via RSS Feed







1.
Pratik | August 8, 2006 at 2:42 pm
def nl2br(s)
s.gsub(/\n/, ”)
end
This would be more appropriate :)
2.
Akhil Bansal | August 18, 2006 at 12:30 pm
This will remove all new line characters not replace them by <br> :-)
3.
Iain | March 4, 2007 at 7:23 pm
s.gsub didnt work for me alone, but
var = s.gsub(/\n/, ”)
did work. Just in case anyone else has the same problem
4.
Marcio Lima | August 12, 2007 at 5:26 am
i`m using
param.gsub(/\n/, ”)
work nice
5.
Kalle | August 20, 2007 at 8:34 pm
Actually… s.gsub(/\n/, ”) vorked like a charm! Thanks man. ;o)
6.
AllForYou123 | August 30, 2007 at 4:39 am
Helo, it is very interesting site. If You want you can visit mine. chain hang jibbs low lyric I have make it myself. There you can find all about chain hang jibbs low lyric etc…
7.
Idetrorce | December 15, 2007 at 12:18 pm
very interesting, but I don’t agree with you
Idetrorce
8.
Wiras Adi | January 15, 2008 at 11:17 am
Don’t you think that it should be something like this:
def nl2br(s)
s.gsub(/(\r)?\n/, “”)
end
Windows has different way of breaking a line, that code will check also for the carriage return Windows used.
9.
Wiras Adi | January 15, 2008 at 11:19 am
Sorry, forgot to escape the br tag.
def nl2br(s)
s.gsub(/(\r)?\n/, “<br />”)
end
10.
Akhil Bansal | January 15, 2008 at 11:27 am
I don’t use windows so I don’t have that idea
11.
Alen | April 5, 2008 at 12:35 pm
Don’t understand why Ruby as a multi-purpose language directly should have such function/method.
If you using Rails web framework, there is a simple_format() method of ActionView::Helpers::TextHelper module that does exactly that and more.
12.
ian | June 2, 2008 at 12:51 pm
if you are using rails you can use the simple_format function in your views.
here’s the source code from the api (http://api.rubyonrails.com/classes/ActionView/Helpers/TextHelper.html#M001057)
def simple_format(text)
content_tag ‘p’, text.to_s.
gsub(/\r\n?/, “\n”).
gsub(/\n\n+/, “\n\n”).
gsub(/([^\n]\n)(?=[^\n])/, ‘\1′)
end