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

2.4k views Asked by At

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
3

There are 3 answers

8
David Ljung Madison Stellar On BEST 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)

1
Atchyut Nagabhairava On

Hope this may help you:

    %{ Multi-line
   string }.squish                   # => "Multi-line string"

" foo   bar    \n   \t   boo".squish # => "foo bar boo"

http://apidock.com/rails/String/squish

1
OMY On

Well I've tested this online, not in my ruby so don't know if it works %100. But from what I've read. Your code saved \r\n\ as a text, and your expected answer shouldn't show them so you have to run the following command:

x.gsub(/[\\r\\n]/,'')

cause \ is used with r & n to define other characters so you first need to discard it first \\ shows the \ character.

  • \\n means "\n" string
  • \n means a new line