module ActionView::Helpers::TextHelper
def highlight(text, phrases, options = {})
highlight('You searched for: rails', 'rails') { |match| link_to(search_path(q: match, match)) }
# => You searched for: rails
highlight('You searched for: rails', 'rails', highlighter: '\1')
# => You searched for: rails
highlight('You searched for: rails', ['for', 'rails'], highlighter: '\1')
# => You searched for: ruby, rails, dhh
highlight('You searched for: ruby, rails, dhh', 'actionpack')
# => You searched for: rails
highlight('You searched for: rails', /for|rails/)
# => You searched for: rails
highlight('You searched for: rails', 'rails')
'\1') or passing a block that receives each matched term.
as a single-quoted string with \1 where the phrase is to be inserted (defaults to
a :highlighter string. The highlighter can be specialized by passing :highlighter
Highlights one or more +phrases+ everywhere in +text+ by inserting it into
def highlight(text, phrases, options = {}) text = sanitize(text) if options.fetch(:sanitize, true) if text.blank? || phrases.blank? text || "" else match = Array(phrases).map do |p| Regexp === p ? p.to_s : Regexp.escape(p) end.join('|') if block_given? text.gsub(/(#{match})(?![^<]*?>)/i) { |found| yield found } else highlighter = options.fetch(:highlighter, '<mark>\1</mark>') text.gsub(/(#{match})(?![^<]*?>)/i, highlighter) end end.html_safe end