From 83a7a698939b5b4cba3c04a86befc12b9005df3d Mon Sep 17 00:00:00 2001 From: Jacob Thornton Date: Mon, 19 Mar 2012 15:33:28 -0700 Subject: [PATCH] typeahead should escape regexp special chars --- js/bootstrap-typeahead.js | 3 ++- js/tests/unit/bootstrap-typeahead.js | 16 ++++++++++++++++ 2 files changed, 18 insertions(+), 1 deletion(-) diff --git a/js/bootstrap-typeahead.js b/js/bootstrap-typeahead.js index dc2f882218..804e60dc44 100644 --- a/js/bootstrap-typeahead.js +++ b/js/bootstrap-typeahead.js @@ -109,7 +109,8 @@ } , highlighter: function (item) { - return item.replace(new RegExp('(' + this.query + ')', 'ig'), function ($1, match) { + var query = this.query.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&') + return item.replace(new RegExp('(' + query + ')', 'ig'), function ($1, match) { return '' + match + '' }) } diff --git a/js/tests/unit/bootstrap-typeahead.js b/js/tests/unit/bootstrap-typeahead.js index 96ea7c45fc..25d313c85c 100644 --- a/js/tests/unit/bootstrap-typeahead.js +++ b/js/tests/unit/bootstrap-typeahead.js @@ -52,6 +52,22 @@ $(function () { typeahead.$menu.remove() }) + test("should not explode when regex chars are entered", function () { + var $input = $('').typeahead({ + source: ['aa', 'ab', 'ac', 'mdo*', 'fat+'] + }) + , typeahead = $input.data('typeahead') + + $input.val('+') + typeahead.lookup() + + ok(typeahead.$menu.is(":visible"), 'typeahead is visible') + equals(typeahead.$menu.find('li').length, 1, 'has 1 item in menu') + equals(typeahead.$menu.find('.active').length, 1, 'one item is active') + + typeahead.$menu.remove() + }) + test("should hide menu when query entered", function () { stop() var $input = $('').typeahead({