Skip to content
This repository was archived by the owner on May 29, 2019. It is now read-only.

Commit 467afcd

Browse files
fix(typeahead): correctly higlight matches if query contains regexp-special chars
Closes #316
1 parent 0618ce4 commit 467afcd

File tree

2 files changed

+34
-1
lines changed

2 files changed

+34
-1
lines changed

src/typeahead/test/typeahead.spec.js

+28
Original file line numberDiff line numberDiff line change
@@ -142,6 +142,34 @@ describe('typeahead tests', function () {
142142
});
143143
});
144144

145+
describe('typeaheadHighlight', function () {
146+
147+
var highlightFilter;
148+
beforeEach(inject(function (typeaheadHighlightFilter) {
149+
highlightFilter = typeaheadHighlightFilter;
150+
}));
151+
152+
it('should higlight a match', function () {
153+
expect(highlightFilter('before match after', 'match')).toEqual('before <strong>match</strong> after');
154+
});
155+
156+
it('should higlight a match with mixed case', function () {
157+
expect(highlightFilter('before MaTch after', 'match')).toEqual('before <strong>MaTch</strong> after');
158+
});
159+
160+
it('should higlight all matches', function () {
161+
expect(highlightFilter('before MaTch after match', 'match')).toEqual('before <strong>MaTch</strong> after <strong>match</strong>');
162+
});
163+
164+
it('should do nothing if no match', function () {
165+
expect(highlightFilter('before match after', 'nomatch')).toEqual('before match after');
166+
});
167+
168+
it('issue 316 - should work correctly for regexp reserved words', function () {
169+
expect(highlightFilter('before (match after', '(match')).toEqual('before <strong>(match</strong> after');
170+
});
171+
});
172+
145173
describe('typeahead', function () {
146174

147175
var $scope, $compile, $document;

src/typeahead/typeahead.js

+6-1
Original file line numberDiff line numberDiff line change
@@ -207,7 +207,12 @@ angular.module('ui.bootstrap.typeahead', [])
207207
})
208208

209209
.filter('typeaheadHighlight', function() {
210+
211+
function escapeRegexp(queryToEscape) {
212+
return queryToEscape.replace(/([.?*+^$[\]\\(){}|-])/g, "\\$1");
213+
}
214+
210215
return function(matchItem, query) {
211-
return (query) ? matchItem.replace(new RegExp(query, 'gi'), '<strong>$&</strong>') : query;
216+
return query ? matchItem.replace(new RegExp(escapeRegexp(query), 'gi'), '<strong>$&</strong>') : query;
212217
};
213218
});

0 commit comments

Comments
 (0)