In Rails - is there a rails method to convert newlines to <br>?

Viewed 54283

Is there a Railsy way to convert \n to <br>?

Currently, I'm doing it like this:

mystring.gsub(/\n/, '<br>')
9 Answers

You may make it more general by doing:

mystring.gsub(/(?:\n\r?|\r\n?)/, '<br>')

This way you would cover DOS, *NIX, Mac and accidental invalid line endings.

You also might consider what you're trying to do - if you're nicely formatting text that people have entered, you might consider a filter like Markdown to let your users format their text without opening up the can of worms that is HTML. You know, like it is here at Stack Overflow.

Nope. What you have there is the commonly used alternative. The definition most people use is:

   def nl2br text
       text.gsub(/\n/, '<br/>')
   end

It is named as such because it mimics the functionality of the PHP function by the same name.

mystring.gsub(/\r\n|\r|\n/, '\n')

worked for me

You can do simple_format(h(text)) – the h will ensure any HTML is not rendered.

As mentioned in other answers, this will do a bit more than you asked for. It wraps the whole thing in <p>, and adds more paragraphs if you have double newlines anywhere.

Another option is just to show the text inside <pre> html5 tag.

The HTML element represents preformatted text which is to be presented exactly as written in the HTML file. The text is typically rendered using a non-proportional ("monospace") font. Whitespace inside this element is displayed as written.

https://developer.mozilla.org/en-US/docs/Web/HTML/Element/pre

Related