1
0

Merge pull request #2 from Gringill/master

Do not split on spaces inside simple and double quotes.
This commit is contained in:
Julien Buty
2015-10-22 11:00:43 +08:00
2 changed files with 50 additions and 2 deletions

View File

@@ -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

View File

@@ -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');
});
});