简体   繁体   中英

Set rails highlight to match only entire words

I'm using highlight method to mark words in texts. So, my problem is when i try to highlight little words that can be "sub-words" than others. Ex.:

highlight("a estimativa de tempo", ["tim", "oi"])

And the highlight returns:

"a es<mark>tim</mark>ativa de tempo"

But i need the highlight method to match only entire words. Ex.:

highlight("a operadora tim", ["tim", "oi"]), returning:
"a operadora <mark>tim</mark>"

highlight("Oi anuncia", ["tim", "oi"]), returning:
"a operadora <mark>tim</mark>"

highlight("Operadora Tim declara", ["tim", "oi"]), returning:
"Operadora <mark>Tim</mark> declara"

The highlight helper accepts regular expressions for the match phrases, so you can wrap each phrase in \\b which is a zero-length word boundary matcher:

highlight("this is a test", [/\bis\b/])
=> "this <mark>is</mark> a test"

You'll notice that only the standalone word "is" is highlighted and not the the "is" within the word "this".

I was going to recommend @infused's method too, but I'd make one small change:

highlight("this Is a test", [/\bis\b/i])
=> "this <mark>Is</mark> a test"

This way it is case-insensitive and fits all your sample cases.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM