Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
require 'nokogiri'
html = "Strange strange Crismas?"
word = "strange"
def highlight(html, word)
n = Nokogiri::HTML::fragment(html).tap do |doc|'.//text()').each do |text_node|
new_contents = text_node.text.gsub(/\b(#{word})\b/i, '<span class="bold">\1</span>')
highlight(html, word)
=> "Strange strange Crismas?"

This comment has been minimized.

Copy link

ChintuKarthi commented Jul 3, 2019

Hey, thanks for the gist. I am facing some issue when there is a '<' in the html input.
When a string like this html = "Strange but the snow is <low than previous Christmas?"
The function is converting the '<' to a tag something like this. < low . >< low >

Is there any way to avoid this?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.