diff --git a/lib/search-query-parser.js b/lib/search-query-parser.js index d5bd2f1..d1f2a4d 100644 --- a/lib/search-query-parser.js +++ b/lib/search-query-parser.js @@ -27,8 +27,34 @@ exports.parse = function (string, options) { else { // Our object to store the query object var query = {text: []}; - // Get a list of search term. Reverse to ensure proper order when pop()'ing. - var terms = string.split(' ').reverse(); + // Get a list of search terms respecting single and double quotes + var terms = string.match(/(\S+:'(?:[^'\\]|\\.)*')|(\S+:"(?:[^"\\]|\\.)*")|\S+|\S+:\S+/g); + for (var i = 0; i < terms.length; i++) { + var sepIndex = terms[i].indexOf(':'); + if(sepIndex !== -1) { + var split = terms[i].split(':'), + key = terms[i].slice(0, sepIndex), + val = terms[i].slice(sepIndex + 1); + // Strip surrounding quotes + val = val.replace(/^\"|\"$|^\'|\'$/g, ''); + // Strip backslashes respecting escapes + val = (val + '').replace(/\\(.?)/g, function (s, n1) { + switch (n1) { + case '\\': + return '\\'; + case '0': + return '\u0000'; + case '': + return ''; + default: + return n1; + } + }); + terms[i] = key + ':' + val; + } + }; + // Reverse to ensure proper order when pop()'ing. + terms.reverse(); // For each search term while (term = terms.pop()) { // Advanced search terms syntax has key and value diff --git a/test/test.js b/test/test.js index 414ab0b..14385a6 100644 --- a/test/test.js +++ b/test/test.js @@ -201,4 +201,26 @@ describe('Search query syntax parser', function () { }); + it('should not split on spaces inside single and double quotes', function () { + var searchQuery = 'name:"Bob Saget" description:\'Banana Sandwiche\''; + var options = {keywords: ['name', 'description']}; + var parsedSearchQuery = searchquery.parse(searchQuery, options); + + parsedSearchQuery.should.be.an.Object; + parsedSearchQuery.should.have.property('name', 'Bob Saget'); + parsedSearchQuery.should.have.property('description', 'Banana Sandwiche'); + }); + + + it('should correctly handle escaped single and double quotes', function () { + var searchQuery = 'case1:"This \\"is\\" \'a\' test" case2:\'This "is" \\\'a\\\' test\''; + var options = {keywords: ['case1', 'case2']}; + var parsedSearchQuery = searchquery.parse(searchQuery, options); + + parsedSearchQuery.should.be.an.Object; + parsedSearchQuery.should.have.property('case1', 'This "is" \'a\' test'); + parsedSearchQuery.should.have.property('case2', 'This "is" \'a\' test'); + }); + + });