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

后端 未结 8 1257
情书的邮戳
情书的邮戳 2020-12-04 11:30

Is there a Railsy way to convert \\n to
?

Currently, I\'m doing it like this:

mystring.gsub(/\\n/, \'
\')
相关标签:
8条回答
  • 2020-12-04 11:37

    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.

    0 讨论(0)
  • 2020-12-04 11:44
    mystring.gsub(/\r\n|\r|\n/, '\n')
    

    worked for me

    0 讨论(0)
  • 2020-12-04 11:47

    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.

    0 讨论(0)
  • 2020-12-04 11:48

    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.

    0 讨论(0)
  • 2020-12-04 11:53

    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.

    0 讨论(0)
  • 2020-12-04 11:58

    Simply use

    white-space: pre-line;
    

    in your css and text will wrap on line breaks.

    0 讨论(0)
提交回复
热议问题