Refactor highlight matched word in string I have following method which highlight matched word in text: 

# Hightlight matched term
#
# Ex(for term: some):
#   "&lt;span class="bold"&gt;Some&lt;/span&gt; CEO Event"
#
def highlight_matched(matched_word, text)
  regex = matched_word.gsub(/\*|\"|\'/, "")
                       .split(" ")
                       .map { |s| "\\b#{s}" }.join('|')

  text.gsub(/(#{regex})/i, '&lt;span class="bold"&gt;\1&lt;/span&gt;')
end


Is there a better solution for that?

I am using it here:

"%s %s" %[highlight_matched(title[0..70]), content_tag(:span, caption, class: 'search-type')]
If text may contain HTML (in that case text is a somewhat misleading variable name) you definitely should use a HTML parser. What about this? (adding a &lt;p&gt; as wrapper, otherwise xpath won't find parent text nodes).

require 'nokogiri'

def highlight(html, word)
  Nokogiri::HTML::fragment("&lt;p&gt;" + html + "&lt;/p&gt;").tap do |doc|
    doc.search('.//text()').each do |text_node|
      new_contents = text_node.text.gsub(/\b(#{word})\b/i, '&lt;span class="bold"&gt;\1&lt;/span&gt;')
      text_node.replace(new_contents)
    end
  end.xpath("p").inner_html
end

puts highlight('&lt;p&gt;&lt;a href="http://runner.com"&gt;Run Rabbit Run&lt;/a&gt;&lt;/p&gt;', "run")
# &lt;p&gt;&lt;a href="http://runner.com"&gt;&lt;span class="bold"&gt;Run&lt;/span&gt;     
# Rabbit &lt;span class="bold"&gt;Run&lt;/span&gt;&lt;/a&gt;&lt;/p&gt;