Rails truncate utility adds special characters

I have this HTML text:

<p> I'm a html &nbsp; text</p> 

To show this on my webpage, I first sanitize it and remove the tags:

 sanitize(best_practice.milestone.description, :tags=>[]) 

Then I show ok, &nbsp; is deleted .

But if I decided to trim the text as follows:

 sanitize(best_practice.milestone.description, :tags=>[]).truncate(30) 

&nbsp; displayed again on my web page. All special characters will actually be visible.

What can I do to avoid truncation to make these special characters visible?

+4
source share
1 answer

Working with disinfectants and trimming can be challenging. There are many different sanitation assistants: h, CGI :: escapeHTML, sanitize, strip_tags, html_safe, etc. Sanitation and truncation do not work well if the string is truncated between the opening and the closing tag or in the middle right of the special HTML character.

The following statement seems to work

 sanitize(text, :tags=>[]).truncate(30, :separator => " ").html_safe 

The focus in the pass a: separator option is to cut off the text in a natural break.

+11
source

Source: https://habr.com/ru/post/1434339/


All Articles