Is there a Railsy way to convert \\n to
?
Currently, I\'m doing it like this:
mystring.gsub(/\\n/, \'
\')
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.
mystring.gsub(/\r\n|\r|\n/, '\n')
worked for me
You should be careful with this when you are dealing with user input.
simple_format
inserts <br>
tags but it will allow other html tags!
When using simple_format, <b>Hello</b>
will be rendered as "Hello", you might not want this.
Instead you can use <%= h(c.text).gsub("\n", "<br>").html_safe %>
h()
will encode the html first, gsub
replaces the line break and html_safe
allows the <br>
tags to be displayed.
This will display exactly what the user entered. It also allows to discuss html in e.g. comments.
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 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.
Simply use
white-space: pre-line;
in your css and text will wrap on line breaks.