From 720f94c6c33841ada6d6f235cb2679bb91a71c19 Mon Sep 17 00:00:00 2001 From: Jake Harding Date: Sun, 3 Mar 2013 10:50:14 -0800 Subject: [PATCH] Escape regex characters when updating hint. Fixes #76. --- src/js/typeahead_view.js | 4 +++- src/js/utils.js | 5 +++++ test/playground.html | 14 ++++++++++++++ test/typeahead_view_spec.js | 16 +++++++++++++++- 4 files changed, 37 insertions(+), 2 deletions(-) diff --git a/src/js/typeahead_view.js b/src/js/typeahead_view.js index a77eddf0..f151fe3b 100644 --- a/src/js/typeahead_view.js +++ b/src/js/typeahead_view.js @@ -95,6 +95,7 @@ var TypeaheadView = (function() { hint = dataForFirstSuggestion ? dataForFirstSuggestion.value : null, inputValue, query, + escapedQuery, beginsWithQuery, match; @@ -103,8 +104,9 @@ var TypeaheadView = (function() { query = inputValue .replace(/\s{2,}/g, ' ') // condense whitespace .replace(/^\s+/g, ''); // strip leading whitespace + escapedQuery = utils.escapeRegExChars(query); - beginsWithQuery = new RegExp('^(?:' + query + ')(.*$)', 'i'); + beginsWithQuery = new RegExp('^(?:' + escapedQuery + ')(.*$)', 'i'); match = beginsWithQuery.exec(hint); this.inputView.setHintValue(inputValue + (match ? match[1] : '')); diff --git a/src/js/utils.js b/src/js/utils.js index 62f3b9c5..00b08173 100644 --- a/src/js/utils.js +++ b/src/js/utils.js @@ -11,6 +11,11 @@ var utils = { isBlankString: function(str) { return !str || /^\s*$/.test(str); }, + // http://stackoverflow.com/a/6969486 + escapeRegExChars: function(str) { + return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, '\\$&'); + }, + isString: function(obj) { return typeof obj === 'string'; }, isNumber: function(obj) { return typeof obj === 'number'; }, diff --git a/test/playground.html b/test/playground.html index 9d4fdfed..068d7f44 100644 --- a/test/playground.html +++ b/test/playground.html @@ -28,6 +28,9 @@

+
+
+ diff --git a/test/typeahead_view_spec.js b/test/typeahead_view_spec.js index 516d00dc..46050fd8 100644 --- a/test/typeahead_view_spec.js +++ b/test/typeahead_view_spec.js @@ -523,8 +523,11 @@ describe('TypeaheadView', function() { }); describe('if top suggestion\'s value begins with query', function() { - it('should show hint', function() { + beforeEach(function() { this.dropdownView.isOpen.andReturn(true); + }); + + it('should show hint', function() { this.inputView.getInputValue.andReturn('san '); this.dropdownView.getFirstSuggestion .andReturn({ value: 'san francisco' }); @@ -534,6 +537,17 @@ describe('TypeaheadView', function() { expect(this.inputView.setHintValue) .toHaveBeenCalledWith('san francisco'); }); + + it('should escape regex characters', function() { + this.inputView.getInputValue.andReturn('*.js(v'); + this.dropdownView.getFirstSuggestion + .andReturn({ value: '*.js(v\\d.\\d.\\d)' }); + + this[view].trigger(eventType); + + expect(this.inputView.setHintValue) + .toHaveBeenCalledWith('*.js(v\\d.\\d.\\d)'); + }); }); describe('if top suggestion\'s value does not begin with query',