abc abc - 4 years ago 129
HTML Question

Replace text with HTML

I have a simple HTML document:

<div should-not-be-replaced=":smile:">
Hello :smile:!
</div>


How would I replace the
:smile:
text with
<img src="smile.png">
, but keeping the first
:smile:
unchanged, to get this:

<div should-not-be-replaced=":smile:">
Hello <img src="smile.png">!
</div>





I tried this, but Nokogiri escapes my HTML as plain text:

doc = Nokogiri::HTML::DocumentFragment.parse(html)
doc.traverse do |x|
next unless x.text?
x.content = x.text.gsub(':smile:', '<img src="smile.png">')
end

Answer Source

My solution is very similar to Ku's, although I've tried to handle situations where the replaced text could be in the source text multiple times by completely replacing the content text with an HTML Doc Fragment

doc = Nokogiri::HTML::DocumentFragment.parse(DATA.read)
doc.traverse do |x|
  next unless x.text?
  if x.text.match(%r{:(\w+):})
    replace_text = x.text.gsub(%r{:(\w+):}, "<img src='#{$1}.png'>")
    x.content = ""
    x.add_next_sibling replace_text
  end
end
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download