Skip to content

Instantly share code, notes, and snippets.

@regedarek
Created December 19, 2012 14:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save regedarek/b5015d8932990efc786b to your computer and use it in GitHub Desktop.
Save regedarek/b5015d8932990efc786b to your computer and use it in GitHub Desktop.
93: def highlight(html, word)
94: doc = Nokogiri::HTML::fragment(html)
95: doc.search('.//text()').each do |text_node|
96: new_html = text_node.text.gsub(/\b(#{word})/i, '<span class="bold">\1</span>')
97: text_node.content = ""
98: text_node.after(new_html)
99: end
=> 100: binding.pry_remote
101: doc.to_s
102: end
[#<Search:0x007fc299d8de58>]>> @term
=> "strange"
[#<Search:0x007fc299d8de58>]>> html
=> "Strange strange Crismas?"
[#<Search:0x007fc299d8de58>]>> word
=> "strange"
[#<Search:0x007fc299d8de58>]>> doc
=> #(DocumentFragment:0x3fe14ced4550 {
name = "#document-fragment",
children = [ #(Text "Strange strange Crismas?")]
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment