public Method

TextHelper.highlight(text, phrases, highlighter = '<strong class="highlight">\1</strong>')

Highlights one or more phrases everywhere in text by inserting it into a highlighter string. The highlighter can be specialized by passing highlighter as a single-quoted string with \1 where the phrase is to be inserted (defaults to ’<strong>\1</strong>’)

Examples

highlight('You searched for: rails', 'rails')
# => You searched for: <strong>rails</strong>

highlight('You searched for: ruby, rails, dhh', 'actionpack')
# => You searched for: ruby, rails, dhh

highlight('You searched for: rails', ['for', 'rails'], '<em>\1</em>')
# => You searched <em>for</em>: <em>rails</em>

highlight('You searched for: rails', 'rails', "<a href="search?q=\1">\1</a>")
# => You searched for: a<a href='search?q=rails>rails</a>

Source Code

# File action_view/helpers/text_helper.rb, line 82
def highlight(text, phrases, highlighter = '<strong class="highlight">\1</strong>')
  if text.blank? || phrases.blank?
    text
  else
    match = Array(phrases).map { |p| Regexp.escape(p) }.join('|')
    text.gsub(/(#{match})/i, highlighter)
  end
end
Comments

Have your say
Please use Textile formatting (click here for a cheat sheet). Use <code/> and <pre/> for code samples.
Click here to login with OpenID to to post comments.