开发者

Ruby TextHelper highlight method with Regexp

开发者 https://www.devze.com 2023-04-11 13:18 出处:网络
I\'m trying to highlight every digit sequence in a text using the Highlight method. I can achieve this passing an array of numbers, but that way each number is highlighted individually. I\'d like to h

I'm trying to highlight every digit sequence in a text using the Highlight method. I can achieve this passing an array of numbers, but that way each number is highlighted individually. I'd like to highlight the whole sequence.

Is it possible to use Highlight with Regexp? I'm receiving the following error:

highl开发者_JAVA百科ight(text,/\d+/)

can't convert Regexp to String

Thanks


Unfortunately not! But you can use the source of the highlight method as inspiration to write your own helper that does exactly what you need.

def highlight_digits(text)
  # Based on ActionView::Helpers::TextHelper#highlight
  highlighter = '<strong class="highlight">\1</strong>'
  matcher = /(\d+)(?!(?:[^<]*?)(?:["'])[^<>]*>)/
  text.gsub(matcher, highlighter).html_safe
end

If you feel comfortable, you can propose a patch to Rails to include this feature!

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号