Module: StringMagic::Formatting::Highlighting

Included in:
StringMagic
Defined in:
lib/string_magic/formatting/highlighting.rb

Instance Method Summary collapse

Instance Method Details

#highlight(text, phrases, options = {}) ⇒ Object



4
5
6
7
8
9
10
11
12
13
14
15
16
# File 'lib/string_magic/formatting/highlighting.rb', line 4

def highlight(text, phrases, options = {})
  return text if text.nil? || phrases.nil?

  tag = options[:tag] || "mark"
  css_class = options[:class]
  phrases = Array(phrases)

  class_attr = css_class ? %( class="#{css_class}") : ""

  phrases.reduce(text) do |result, phrase|
    result.gsub(/(#{Regexp.escape(phrase)})/i, "<#{tag}#{class_attr}>\\1</#{tag}>")
  end
end