sam sam - 4 months ago 26
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

\r
\n
— 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

\r\n\r\n

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

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!)

Example:

@attraction.description.gsub(/\r\n/,'')

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

@attraction.description.gsub(/[\r\n]/,'')

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:

@attraction.description.gsub(/\\[rn]/,'').html_safe

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

Comments