instance method highlight

Ruby on Rails 8.1.4.1

Available in: v2.2.3 v2.3.18 v3.0.20 v3.1.12 v3.2.22.5 v4.0.13 v4.1.16 v4.2.11.3 v5.0.7.2 v5.1.7 v5.2.8.1 v6.0.6.1 v6.1.7.10 v7.0.10 v7.1.6 v7.2.4 v8.0.5.2 v8.1.4.1 edge

Signature

highlight(text, phrases, options = {}, &block)

Highlights occurrences of phrases in text by formatting them with a highlighter string. phrases can be one or more strings or regular expressions. The result will be marked HTML safe. By default, text is sanitized before highlighting to prevent possible XSS attacks.

If a block is specified, it will be used instead of the highlighter string. Each occurrence of a phrase will be passed to the block, and its return value will be inserted into the final result.

Options
:highlighter

The highlighter string. Uses \1 as the placeholder for a phrase. Defaults to "<mark>\1</mark>". The numbered placeholders \0 to \9 are expanded; other +String#sub+ replacement escapes are not. The phrase is HTML escaped, quotes included. This option is ignored if a block is specified.

WARNING: Put a placeholder only in element content or inside a quoted attribute value. HTML escaping does not make the phrase safe in an unquoted attribute value, in a URL, JavaScript or CSS context, or in an attribute whose value is HTML, such as srcdoc.

:sanitize

Whether to sanitize text before highlighting. Defaults to true.

Examples
highlight('You searched for: rails', 'rails')
# => "You searched for: <mark>rails</mark>"

highlight('You searched for: rails', /for|rails/)
# => "You searched <mark>for</mark>: <mark>rails</mark>"

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

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

highlight('You searched for: rails', 'rails', highlighter: '<mark title="\1">\1</mark>')
# => "You searched for: <mark title=\"rails\">rails</mark>"

highlight('You searched for: rails', 'rails') { |match| link_to(search_path(q: match)) }
# => "You searched for: <a href=\"search?q=rails\">rails</a>"

highlight('<a href="javascript:alert(\'no!\')">ruby</a> on rails', 'rails', sanitize: false)
# => "<a href=\"javascript:alert('no!')\">ruby</a> on <mark>rails</mark>"

Parameters

text req
phrases req
options opt = {}
block block
Source
# File actionview/lib/action_view/helpers/text_helper.rb, line 181
      def highlight(text, phrases, options = {}, &block)
        text = sanitize(text) if options.fetch(:sanitize, true)

        if text.blank? || phrases.blank?
          text || ""
        else
          patterns = Array(phrases).map { |phrase| Regexp === phrase ? phrase : Regexp.escape(phrase) }
          pattern = /(#{patterns.join("|")})/i
          # The text after a tag begins with the ">" that closes it. Leave it
          # in the segment so phrases can see it as context, but keep it out
          # of the match so the highlighter can't take the place of the ">".
          pattern_after_tag = /(?!\A)#{pattern}/
          highlighter = options.fetch(:highlighter, '<mark>\1</mark>') unless block

          text.scan(/<[^>]*|[^<]+/).each_with_index do |segment, index|
            if !segment.start_with?("<")
              segment_pattern = index > 0 ? pattern_after_tag : pattern

              if block
                segment.gsub!(segment_pattern, &block)
              else
                segment.gsub!(segment_pattern) do
                  match = Regexp.last_match
                  highlighter.gsub(/\\(\d)/) { ERB::Util.html_escape_once(match[$1.to_i]) }
                end
              end
            end
          end.join
        end.html_safe
      end

Defined in actionview/lib/action_view/helpers/text_helper.rb line 181 · View on GitHub · Improve this page · Find usages on GitHub

Defined in ActionView::Helpers::TextHelper

Type at least 2 characters to search.

Use the arrow keys to navigate results, Enter to open one, Escape to close.

Keyboard shortcuts

/
Focus search
⌘K / Ctrl-K
Command palette
?
This help
Esc
Close