Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace html tags with whitespaces

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" 
like image 953
Avdept Avatar asked Aug 29 '26 23:08

Avdept


1 Answers

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"
like image 80
vee Avatar answered Aug 31 '26 18:08

vee



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!