Last active
September 7, 2016 05:26
-
-
Save nackjicholson/4d1452b2eaeacbb534558a272db7b26e to your computer and use it in GitHub Desktop.
search term regex from the gods
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Beautiful regex patterns that parse and validate complex querystring parameter of search terms | |
const searchSyntaxValidationRegex = /^([^:]+:[^:]+(?:,|$))+$/; | |
const searchSyntaxParseRegex = /([^:]+):\(([^(]+)\)(?:,|$)/g; | |
/** | |
* Parses comma separated list of key values into an object. | |
* | |
* IN: | |
* title:(bar bar),content_stripped:(baz, and qux),other:(beep boop) | |
* | |
* OUT: | |
* { title: 'bar bar', content_stripped: 'baz, and qux', other: 'beep boop' } | |
* | |
* @param {string} str | |
* | |
* @returns {object} | |
*/ | |
function searchTermStringToObject(str) { | |
const obj = {}; | |
if (!str) { | |
return obj; | |
} | |
let match; | |
while ((match = searchSyntaxParseRegex.exec(str))) { | |
// match[1] is key, match[2] is value | |
obj[match[1]] = match[2]; | |
} | |
return obj; | |
} | |
/** | |
* Parses comma separated list of key values into a collection of query objects with the given type. | |
* | |
* IN: | |
* queryType = 'match' | |
* str = title:(bar bar),content_stripped:(baz, and qux),other:(beep boop) | |
* | |
* OUT: | |
* [ | |
* { match: { title: 'bar bar' } }, | |
* { match: { content_stripped: 'baz, and qux' } }, | |
* { match: { other: 'beep boop' } } | |
* ] | |
* | |
* @param {string} queryType | |
* @param {string} str | |
* | |
* @returns {array} | |
*/ | |
function searchTermToQueryCollection(queryType, str = '') { | |
const collection = []; | |
let match; | |
while ((match = searchSyntaxParseRegex.exec(str))) { | |
const key = match[1]; | |
const value = match[2]; | |
collection.push({ [queryType]: { [key]: value } }); | |
} | |
return collection; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment