Highlight Search Term in Ember

A few months ago I built contacts search into morse.io, which is an Ember project.

Given a contact search was matched by either first name, last name or email address, I wanted to highlight the matched term (e.g. the reason a given contact was returned).

Thus, here is a simple way to highlight matched search terms in Ember.

1: Perform search, pass searchQuery to each result

Naturally, you first need to perform the search query. No changes to how you would normally query:

1
2
3
  store.find('contact', {search: query}).then(function(contacts) {
    //do something
  });

When rendering each result, pass the searchQuery to each result/component. In the context of morse.io, it looks a little like this:

{{contact-card
    action="selectContact"
    contact=contact
    query=searchQuery}}

2: Register a helper to highlight the result

I kept this simple, wrap each matched term in a highight span.

1
2
3
4
5
6
7
8
import Ember from "ember";

export default Ember.Handlebars.makeBoundHelper(function(value, options) {
    var query = options.hash.query;
    var regex = new RegExp(query, "gi");
    var formattedTag = value.replace(regex, "<span class='highlight'>$&</span>");
    return new Handlebars.SafeString(formattedTag);
});

3: Glue time

There is only one functional component left. Instead of placing contact.name and contact.email in the component, let the helper wrap matching query terms in highlight spans.

{{highlight-term contact.name query=query}}

4: Style at will

I like to shade the matching terms with a light yellow:

1
2
3
.highlighted {
  background-color: #F8F2C0;
}