I'm using method strip_tags which removes all tags from my string, however after removing some of my text lacking of whitespaces, especially where 1 tag ends and another begins. Is there any way to insert whitespaces into place where tags were removed? Look for ex. below
str
=> "<span>Class GOesHere</span><div>SomeExtra Tag</div>"
helper.strip_tags(str)
=> "Class GOesHereSomeExtra Tag"
I would recommend parsing the HTML and extracting the text. Nokogiri, a very well known gem should help solve this with ease:
require 'nokogiri'
=> false
> str = "<span>Class GOesHere</span><div>SomeExtra Tag</div>"
=> "<span>Class GOesHere</span><div>SomeExtra Tag</div>"
> Nokogiri::HTML(str).text
=> "Class GOesHereSomeExtra Tag"
Update:
This will search all text nodes in the html and map the text content. The resultant array is concatenated with a space separator:
> Nokogiri::HTML(str).xpath('//text()').map(&:text).join(' ')
=> "Class GOesHere SomeExtra Tag"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With