Get word at cursor
Get the entire word near the cursor position
by th3uiguy
HTML
<div class="form">
<input id="textArea" type="text" value=" Some sample text " onclick="outputWord()" onkeyup="outputWord()" />
<div class="resultDiv">
Result: <span id="result"></span>
</div>
</div>
SCSS
.form{
padding: 10px;
input{
font-size: 15px;
}
.resultDiv{
margin-top: 8px;
color:#aaa;
#result{
color:#000;
}
}
}
JavaScript
function getWord(text, caretPos) {
const index = text.indexOf(caretPos);
const preText = text.substring(0, caretPos);
const aftText = text.substring(caretPos);
const charAft = aftText && aftText.charAt(0);
const hasCharsAfter = charAft && charAft.match(/\S/);
if (preText && preText.charAt(preText.length -1) || hasCharsAfter) {
const preWords = preText.split(/\s/);
let word = preWords[preWords.length - 1];
if(hasCharsAfter){
const aftWords = aftText.split(/\s/);
word += aftWords[0];
}
return word;
}
return preText || "";
}
function outputWord() {
const el = document.getElementById("textArea");
const caretPos = getCaretPosition(el)
const word = getWord(el.value, caretPos);
document.getElementById("result").innerHTML = word;
}
function getCaretPosition(ctrl) {
let CaretPos = 0; // IE Support
if (document.selection) {
ctrl.focus();
var Sel = document.selection.createRange();
Sel.moveStart('character', -ctrl.value.length);
CaretPos = Sel.text.length;
}
// Firefox support
else if (ctrl.selectionStart || ctrl.selectionStart == '0'){
CaretPos = ctrl.selectionStart;
}
return CaretPos;
}