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:
span
tagspan
tag has a special highlight class attached to it for cosmeticsRegular 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.