Topic: String Replace/Replace "\n" with "</div><div>"

The subject basically says what I want to do. I either need the equivelant to PHP's str_replace(), or a fancy method that will take a text box feed and apply HTML tags to it (the opposite of strip_tags).


Re: String Replace/Replace "\n" with "</div><div>"

puts "text\n newline".gsub /\n/, "</div><div>"

or maybe Textile will sui you?

Re: String Replace/Replace "\n" with "</div><div>"

I'd definitely recommend Textile for this.  It makes natural text look good.

But if you want to do it yourself I recommend splitting the string rather than a str_replace style.

text = text.split "/n"
text = text.collect {/line/ "<div>#{line}</div>" }

Sorry about the /line/ part - that was supposed to be vertical pipes but I can't find the symbol on my phone :-(

Re: String Replace/Replace "\n" with "</div><div>"

Thanks! I ended up going with the following for formatting reasons:

self.content = self.content.gsub("\n", "<br />")

I may integrate Textile in the future, but for now, this is all the functionality that I need.

The code danger gave me had some really weird results that weren't anything like what I was expecting or wanting. (Threw in some "--- -" stuff at the beginning, and wrapped the entire text in div tags, not on the line breaks.)

Last edited by KittyKate (2006-11-24 13:57:37)

Re: String Replace/Replace "\n" with "</div><div>"

Danger's code ends in an array, so you would need to join it at the end:


Railscasts - Free Ruby on Rails Screencasts

Re: String Replace/Replace "\n" with "</div><div>"

Right, thanks Ryan.  I gotta stop trying to write whole posts on a little keyboard - it's bound for failure :-)