Search code examples
ember.jshandlebars.jsember-cli

How to highlight a given word inside hbs?


Is there any way to highlight a given word inside an ember template?

Example:

var givenWord = "hello"

ember template is as follows:

<div>
<p>some text here, some another text with hello, again hello</p>
</div>

I want to apply specific CSS to the word hello (this word is dynamic) Appreciate any help!


Solution

  • Found the solution using handlebar helpers

       Ember.Handlebars.helper('highlightMatchingText', function (text, phrase) {
        var highlightedText = text.replace(new RegExp(phrase, 'gi'), function (str) {
            return '<span class="color-red">' + str + '</span>';
        });
      return new Ember.Handlebars.SafeString(highlightedText);
    });
    

    then we can call this inside hbs as follows

    {{highlightMatchingText "text goes here" "hello"}}
    

    NOTE: i'm using ember 0.2.5