Skip to content

Instantly share code, notes, and snippets.

@pyxze
Created October 25, 2013 21:15
Show Gist options
  • Save pyxze/7161956 to your computer and use it in GitHub Desktop.
Save pyxze/7161956 to your computer and use it in GitHub Desktop.
JavaScript function I wrote to parse "and" and "or" into proper regex for use with Datatables.
// QUnit tests.
// test("datatables parser", function() {
// equal(datatablesParser("austin"), "austin");
// equal(datatablesParser("houston or austin"), "houston|austin");
// equal(datatablesParser("houston and austin or dallas"), "^(?=.*?\\bhouston\\b)(?=.*?\\baustin\\b).*$|^(?=.*?\\bdallas\\b).*$");
// equal(datatablesParser("houston and austin or dallas and austin"), "^(?=.*?\\bhouston\\b)(?=.*?\\baustin\\b).*$|^(?=.*?\\bdallas\\b)(?=.*?\\baustin\\b).*$");
// equal(datatablesParser("houston or austin or dallas"), "houston|austin|dallas");
// });
function datatablesParser(string) {
alphastring = string;
orstrings = [];
// Descend into orland
if (alphastring.match(/ [oO][rR] /) && alphastring.match(/ [oO][rR] /).index > -1) {
while (string.match(/ [oO][rR] /)) {
orstrings.push(string.substr(0, string.match(/ [oO][rR] /).index));
string = string.substr(string.match(/ [oO][rR] /).index + 4);
}
orstrings.push(string);
} else {
orstrings = [string];
}
// Descend into andland
if (alphastring.match(/ [aA][nN][dD] /) && alphastring.match(/ [aA][nN][dD] /).index > -1) {
andstrings = [];
for (var i = 0, len = orstrings.length; i < len; i++) {
andstrings.push("^");
while (orstrings[i].match(/ [aA][nN][dD] /)) {
andstrings.push("(?=.*?\\b" + orstrings[i].substr(0, orstrings[i].match(/ [aA][nN][dD] /).index) + "\\b)");
orstrings[i] = orstrings[i].substr(orstrings[i].match(/ [aA][nN][dD] /).index + 5);
}
andstrings.push("(?=.*?\\b" + orstrings[i] + "\\b)");
andstrings.push(".*$");
if (i != len - 1) {
andstrings.push("|");
}
}
return andstrings.join("");
} else {
omegastring = "";
for (var i = 0, len = orstrings.length; i < len; i++) {
omegastring += orstrings[i];
if (i != len - 1) {
omegastring += "|";
}
}
return omegastring;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment