ruby-on-railshighlightactionviewactionviewhelper

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"

Solution

  • 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.