JSFiddle - React, Tailwind, and code Playground
CSS
pre {outline: 1px solid #ccc; padding: 5px; margin: 5px; }
.string { color: green; }
.number { color: darkorange; }
.boolean { color: blue; }
.null { color: magenta; }
.key { color: red; }
JavaScript
var sql = "SELECT pillers, Balloons, Tacks FROM the_database_file WHERE Balloons != 'small' AND Balloons != 'large' AND Blah = 'bobby';";
function parseSql(sql) {
var found = [];
["SELECT", "WHERE", "FROM", "AND", "OR", ";"].forEach(function(word) {
var idx = sql.indexOf(word);
while(idx!==-1) {
found.push({word:word, index:idx});
idx = sql.indexOf(word, idx + 1);
keptIdx = idx;
}
});
found.sort(function(x,y) { return x.index - y.index });
found.forEach(function(x, i, xs) {
if (i < xs.length - 1) {
x.text = sql.substring(x.index, xs[i + 1].index).replace(xs[i].word, "").trim();
}
});
return found;
}
/*****************************************************************
************************** OTHER CODE ****************************
*****************************************************************/
$(document).ready(function() {
var output = JSON.stringify(parseSql(sql), null, 4);
output = syntaxHighlight(output);
document.body.appendChild(document.createElement('pre')).innerHTML = output;
});
function syntaxHighlight(json) {
json = json.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
return json.replace(/("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/g, function (match) {
var cls = 'number';
if (/^"/.test(match)) {
if (/:$/.test(match)) {
cls = 'key';
} else {
cls = 'string';
}
} else if (/true|false/.test(match)) {
cls = 'boolean';
} else if (/null/.test(match)) {
cls = 'null';
}
return '<span class="' + cls + '">' + match + '</span>';
});
}