sam sam - 1 year ago 75
Ruby Question

Unwanted characters - \r \n getting inserted into db - i need to remove them on my view page

I used html_safe, raw and also sanitize. But I still characters like

— this is because i use "return/enter" key in Mac to go to next line when i enter data to my description field - which is textarea. Is there anyway to avoid these in my view page.

actual result -

\r\ntext text text text text text


this place is famous for blah blah blah

expected result-

text text text text text text

this place is famous for blah blah blah

Answer Source

Your options are to either strip the characters before you insert them into the DB, or else strip them in the view.

Either way, you can do this with gsub - your comment above shows that you were using gsub improperly (remember to post what you have tried in your question as well as the results!)



This will only replace a carriage return followed by a newline, I suggest instead replacing any newline/carriage returns:


If you want to replace with:

@attraction.description.gsub(/[\r\n]+/,'<br />').html_safe

And so forth..

On the other hand, if you are actually seeing the text "\r\n" in your output, then you have somehow converted the carriage returns and newlines into their "typable" counterparts, possibly with something like an str.inspect call before storing them?

If that's the case, then you want to replace not carriage returns and newlines, but the strings "\r" and "\n", for example:


(You were putting your regexp in quotes for gsub, making it a string comparison as opposed to a regexp)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download