I\'m building a Sql query builder and would like to change the text color of a word in a textarea when the user types in words like SELECT, FROM, WHERE.
I\'ve searche
With Vanilla JS, you can do it as:
// SQL keywords
var keywords = ["SELECT", "FROM", "WHERE", "LIKE", "BETWEEN", "UNION", "FALSE", "NULL", "FROM", "TRUE", "NOT", "ORDER", "GROUP", "BY", "NOT", "IN"];
// Keyup event
document.querySelector('#editor').addEventListener('keyup', e => {
// Space key pressed
if (e.keyCode == 32) {
var newHTML = "";
// Loop through words
str = e.target.innerText;
chunks = str
.split(new RegExp(
keywords
.map(w => `(${w})`)
.join('|'), 'i'))
.filter(Boolean),
markup = chunks.reduce((acc, chunk) => {
acc += keywords.includes(chunk.toUpperCase()) ?
`${chunk}` :
`${chunk}`
return acc
}, '')
e.target.innerHTML = markup;
// Set cursor postion to end of text
// document.querySelector('#editor').focus()
var child = e.target.children;
var range = document.createRange();
var sel = window.getSelection();
range.setStart(child[child.length - 1], 1);
range.collapse(true);
sel.removeAllRanges();
sel.addRange(range);
this.focus();
}
});
#editor {
width: 400px;
height: 100px;
padding: 10px;
background-color: #444;
color: white;
font-size: 14px;
font-family: monospace;
}
.statement {
color: orange;
}