How to detect and select the last written word when TAB is pressed in a textarea or contenteditable div?
I started to do it with a buffer of the last characters written or key-presses, but then I noticed that there are multiple corner cases:
let's say the user writes HELLUBACKSPACEO
the user moves with arrow keys
the user can separate words with SPACE (that's what I was using) but also ENTER or a comma, etc.
Is there a nice way to detect the last written word?
Goal: to code an autocomplete feature, example: thx + <TAB> => Text is replaced by "Thank you very much."
You can use current cursor position to detect last word. A simple example is given bellow.
document.getElementById('foobar').addEventListener('keydown', e => {
if( e.which == 9 ) {
e.preventDefault();
let endingIndex = e.target.selectionStart;
let startingIndex = endingIndex && endingIndex - 1;
let value = e.target.value;
// putt all delemeters in it by which word can be splitted
let regex = /[ ]/;
while(startingIndex > -1){
if(regex.test(value[startingIndex])){
++startingIndex;
break;
}
--startingIndex;
}
// note you will have you apply check to avoid negative index
if(startingIndex < 0) {
startingIndex = 0;
}
console.log(value.substring(startingIndex, endingIndex));
let newText = "replaced";
value = value.substring(0, startingIndex) + newText + value.substring(endingIndex);
let cursorPosition = startingIndex + newText.length;
e.target.value = value;
e.target.setSelectionRange(cursorPosition, cursorPosition);
}
});
<textarea id="foobar"></textarea>
This totally works for textarea and for contenteditable div:
var newText = 'hello\nnewline';
var newHtml = '<b>test</b> and<br>a <a href="hjkh">link</a>';
document.addEventListener("keydown", function(e) {
var elt = e.target;
if (elt.tagName.toLowerCase() === 'textarea' || elt.isContentEditable)
{
if (e.keyCode == 9) {
e.preventDefault();
if (elt.isContentEditable) { // for contenteditable
elt.focus();
sel = document.getSelection();
sel.modify("extend", "backward", "word");
range = sel.getRangeAt(0);
console.log(range.toString().trim());
range.deleteContents();
var el = document.createElement("div");
el.innerHTML = newHtml;
var frag = document.createDocumentFragment(), node;
while (node = el.firstChild) {
frag.appendChild(node);
}
range.insertNode(frag);
range.collapse();
} else { // for texterea/input element
var endingIndex = elt.selectionStart;
var startingIndex = endingIndex && endingIndex - 1;
var value = elt.value;
var regex = /[ ]/;
while (startingIndex > -1) {
if (regex.test(value[startingIndex])) {
++startingIndex;
break;
}
--startingIndex;
}
if (startingIndex < 0) {
startingIndex = 0;
}
value = value.substring(0, startingIndex) + newText + value.substring(endingIndex);
var cursorPosition = startingIndex + newText.length;
e.target.value = value;
e.target.setSelectionRange(cursorPosition, cursorPosition);
}
}
}
});
<div contenteditable>Hello, press TAB to replace this WORD<br>Also press TAB after this ONE</div>
<textarea rows="8" cols="50" id="a">Hello, press TAB to replace this WORD
Also press TAB after this ONE</textarea>
来源:https://stackoverflow.com/questions/50794324/detect-the-last-written-word-when-typing-tab-in-a-textarea-or-contenteditable-di