module ActionView::Helpers::TextHelper
def highlight(text, phrases, options = {})
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', 'rails')
'\1')
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 highlighter = options.fetch(:highlighter, '<mark>\1</mark>') match = Array(phrases).map { |p| Regexp.escape(p) }.join('|') text.gsub(/(#{match})(?![^<]*?>)/i, highlighter) end.html_safe end