Skip to content

Instantly share code, notes, and snippets.

@drmcarvalho
Last active August 10, 2021 01:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save drmcarvalho/954c30d7dad3a9c17ea47dad86c12d57 to your computer and use it in GitHub Desktop.
Save drmcarvalho/954c30d7dad3a9c17ea47dad86c12d57 to your computer and use it in GitHub Desktop.
Mini parse em js
const regexp = /(\w+?\:|[=><]{1,2}|\S+|\s+(AND|OR)\s+)/g;
const input = 'quantity:>10 AND type:(1,2,3) AND group:>=1 AND nome:"Gato"';
const results = input.match(regexp);
const data = [];
console.log(results); //Debug
for (let i = 0, j = results.length; i < j; i++) {
const current = results[i].trim();
console.log(current); //debug
if (current.indexOf(":") !== -1) {
const item = current.split(":");
data.push({ field: item[0], value: item[1] });
} else {
data[data.length - 1].sibling = current;
}
}
console.log(JSON.stringify(data, " ", 4));
/*
[
{
"field": "quantity",
"value": ">10",
"sibling": "AND"
},
{
"field": "type",
"value": "(1,2,3)",
"sibling": "AND"
},
{
"field": "group",
"value": ">=1",
"sibling": "AND"
},
{
"field": "nome",
"value": "\"Gato\""
}
]
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment