I used setCaretToTextEnd()
from here and .selectRange()
from here. The following functions use Emacs style caret positions, and is more efficient than looping through words.
function nextWord(input) {
let currentCaretPosition = input.selectionStart;
// -1 Because Emacs goes to end of next word.
let nextWordPosition = input.value.indexOf(' ', currentCaretPosition) - 1;
if (nextWordPosition < 0) {
input.setCaretToTextEnd();
} else {
input.selectRange(nextWordPosition);
}
}
function previousWord(input) {
let currentCaretPosition = input.selectionStart;
// +1 Because Emacs goes to start of previous word.
let previousWordPosition = input.value.lastIndexOf(' ', currentCaretPosition) + 1;
if (previousWordPosition < 0) {
input.selectRange(0);
} else {
input.selectRange(previousWordPosition);
}
}