3

Given the following text in a textarea:

Line 1 stuff.. Line 1 stuff.. Line 1 stuff.. Line 1 stuff.. Line 1 stuff.. 

Line 2 stuff.. Line 2 stuff.. Line 2 stuff.. Line 2 stuff.. Line 2 stuff.. 

I want to convert the new lines to <BR> tags, not use the simple_format <P> tags...

So I tried:

 str = str.gsub("\r\n", '<br>')

Problem is this is making two <BR> tags:

<div class="message">line 1<br><br>Line 2</div>

How can make just one <BR> tag?

the Tin Man
  • 158,662
  • 42
  • 215
  • 303
AnApprentice
  • 108,152
  • 195
  • 629
  • 1,012
  • possible duplicate of [Rails 3: How to display properly text from "textarea"?](http://stackoverflow.com/questions/5852377/rails-3-how-to-display-properly-text-from-textarea) – Mark Thomas Jan 20 '12 at 23:02
  • [`
    `](http://brainstormsandraves.com/articles/semantics/structure/#br) used this way isn't [semantic](http://webstyleguide.com/wsg3/5-site-structure/2-semantic-markup.html); use something more appropriate, such as a paragraph or [list](http://www.w3.org/TR/html401/struct/lists.html) element.
    – outis Jan 21 '12 at 19:00
  • possible duplicate of [In Rails - is there a rails method to convert newlines to
    ?](http://stackoverflow.com/questions/611609/), [Ruby on Rails: How can i convert/replace every newline to '
    '?](http://stackoverflow.com/questions/8405175/)
    – outis Jan 21 '12 at 19:02

4 Answers4

7

Best way to do this is to use simple_format(str):

simple_format() is a helper function which will convert new lines and carriage returns to <br> and <p>...</p> tags.

reference: http://api.rubyonrails.org/classes/ActionView/Helpers/TextHelper.html#method-i-simple_format

Christopher Oezbek
  • 23,994
  • 6
  • 61
  • 85
6
str = str.gsub(/[\r\n]+/, "<br>")

This will turn any number of consecutive \r and/or \n characters into a single <br>.

criticabug
  • 331
  • 6
  • 12
Alex D
  • 29,755
  • 7
  • 80
  • 126
1

This would mean that you have two occurrences of "\r\n". So you could sanitize the input or expect this situation in your regex.

Have a look at this: Ruby gsub / regex modifiers?

Community
  • 1
  • 1
mkro
  • 1,902
  • 14
  • 15
0

You have two line breaks in the input text. If you want there to be one <br/>, just do:

str = str.gsub("\r\n\r\n", '<br />');
personak
  • 539
  • 4
  • 15