Our website is made possible by displaying online advertisements to our visitors. Please consider supporting us by disabling your ad blocker.

Highlight Text In A String Using JavaScript And AngularJS

TwitterFacebookRedditLinkedInHacker News

Have you ever wanted to highlight text in a string on a web page using AngularJS? If your answer was no, don’t disregard, because you may one day need to. The good thing is this is not very hard to accomplish.

There are many ways to do this using JavaScript, but we’re only going to examine one of those methods.

Using AngularJS and a few regular expressions (RegEx) with JavaScript, you can find text in a string and then apply your own customizations.

The logic behind this example will be as follows:

  1. Use a regular expression to find a needle in a haystack
  2. Replace the needles found with the same needle wrapped in a span tag
  3. The span tag has a special highlight class attached to it for cosmetics
  4. Return the revised haystack as trusted HTML

Regular expressions (RegEx) via Wikipedia:

A sequence of characters that forms a search pattern, mainly for use in pattern matching with strings, or string matching, i.e. “find and replace”-like operations.

So what does this code look like?:

$scope.highlight = function(haystack, needle) {
    if(!needle) {
        return $sce.trustAsHtml(haystack);
    }
    return $sce.trustAsHtml(haystack.replace(new RegExp(needle, "gi"), function(match) {
        return '<span class="highlightedText">' + match + '</span>';
    }));
};

The highlightedText class is as follows:

.highlightedText {
    background: yellow;
}

When it comes to the front-end, we can add the following code:

<div ng-bind-html="highlight('Nic is cool and smart', 'and')"></div>

That will highlight all the and words in our text. Of course our haystack can be dynamic, but this is just a short example so I’ve left it static text.

There are other ways to highlight text on a page. Of course you can choose to alter the DOM, but I’ve chosen just to leverage the power of RegEx.

Nic Raboy

Nic Raboy

Nic Raboy is an advocate of modern web and mobile development technologies. He has experience in C#, JavaScript, Golang and a variety of frameworks such as Angular, NativeScript, and Unity. Nic writes about his development experiences related to making web and mobile development easier to understand.