Disabling the @uri response in this thread, I changed it to work with a single string OR a string array.
Here is TypeScript version
module myApp.Filters.Highlight { "use strict"; class HighlightFilter {
What translates to JavaScript :
var myApp; (function (myApp) { var Filters; (function (Filters) { var Highlight; (function (Highlight) { "use strict"; var HighlightFilter = (function () { function HighlightFilter($sce) { // The `terms` could be a string, or an array of strings, so we have to use the `any` type here /* tslint:disable: no-any */ return function (str, terms) { /* tslint:enable */ if (terms) { var allTermsRegexStr; if (typeof terms === "string") { allTermsRegexStr = terms; } else { // Sort array by length then join with regex pipe separator allTermsRegexStr = terms.sort(function (a, b) { return b.length - a.length; }).join('|'); } //Escape characters that have meaning in regular expressions //via: http://stackoverflow.com/a/6969486/79677 allTermsRegexStr = allTermsRegexStr.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&"); // Regex to simultaneously replace terms - case insensitive! var regex = new RegExp('(' + allTermsRegexStr + ')', 'ig'); return $sce.trustAsHtml(str.replace(regex, '<mark class="highlight">$&</mark>')); } else { return str; } }; } //This will wrap matching search terms with an element to visually highlight strings //Usage: {{fullString | highlight:'partial string'}} //Usage: {{fullString | highlight:['partial', 'string, 'example']}} HighlightFilter.$inject = ["$sce"]; return HighlightFilter; })(); angular.module("myApp").filter("highlight", HighlightFilter); })(Highlight = Filters.Highlight || (Filters.Highlight = {})); })(Filters = myApp.Filters || (myApp.Filters = {})); })(myApp|| (myApp= {})); ;
Or if you just want a simple JavaScript implementation without these generated namespaces:
app.filter('highlight', ['$sce', function($sce) { return function (str, terms) { if (terms) { var allTermsRegexStr; if (typeof terms === "string") { allTermsRegexStr = terms; } else { // Sort array by length then join with regex pipe separator allTermsRegexStr = terms.sort(function (a, b) { return b.length - a.length; }).join('|'); } //Escape characters that have meaning in regular expressions //via: http://stackoverflow.com/a/6969486/79677 allTermsRegexStr = allTermsRegexStr.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&"); // Regex to simultaneously replace terms - case insensitive! var regex = new RegExp('(' + allTermsRegexStr + ')', 'ig'); return $sce.trustAsHtml(str.replace(regex, '<mark class="highlight">$&</mark>')); } else { return str; } }; }]);
EDITED to include a patch that was previously broken, someone was looking for it . or any other character that matters in a regular expression. Now these characters are escaped first.
Chris Barr Jul 28 '15 at 12:54 2015-07-28 12:54
source share