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

Commit

Permalink
fix(typeahead): correctly higlight matches if query contains regexp-s…
Browse files Browse the repository at this point in the history
…pecial chars

Closes #316
  • Loading branch information
pkozlowski-opensource committed Apr 12, 2013
1 parent 0618ce4 commit 467afcd
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 1 deletion.
28 changes: 28 additions & 0 deletions src/typeahead/test/typeahead.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -142,6 +142,34 @@ describe('typeahead tests', function () {
});
});

describe('typeaheadHighlight', function () {

var highlightFilter;
beforeEach(inject(function (typeaheadHighlightFilter) {
highlightFilter = typeaheadHighlightFilter;
}));

it('should higlight a match', function () {
expect(highlightFilter('before match after', 'match')).toEqual('before <strong>match</strong> after');
});

it('should higlight a match with mixed case', function () {
expect(highlightFilter('before MaTch after', 'match')).toEqual('before <strong>MaTch</strong> after');
});

it('should higlight all matches', function () {
expect(highlightFilter('before MaTch after match', 'match')).toEqual('before <strong>MaTch</strong> after <strong>match</strong>');
});

it('should do nothing if no match', function () {
expect(highlightFilter('before match after', 'nomatch')).toEqual('before match after');
});

it('issue 316 - should work correctly for regexp reserved words', function () {
expect(highlightFilter('before (match after', '(match')).toEqual('before <strong>(match</strong> after');
});
});

describe('typeahead', function () {

var $scope, $compile, $document;
Expand Down
7 changes: 6 additions & 1 deletion src/typeahead/typeahead.js
Original file line number Diff line number Diff line change
Expand Up @@ -207,7 +207,12 @@ angular.module('ui.bootstrap.typeahead', [])
})

.filter('typeaheadHighlight', function() {

function escapeRegexp(queryToEscape) {
return queryToEscape.replace(/([.?*+^$[\]\\(){}|-])/g, "\\$1");
}

return function(matchItem, query) {
return (query) ? matchItem.replace(new RegExp(query, 'gi'), '<strong>$&</strong>') : query;
return query ? matchItem.replace(new RegExp(escapeRegexp(query), 'gi'), '<strong>$&</strong>') : query;
};
});

0 comments on commit 467afcd

Please sign in to comment.