Okay, I’ve been looking all over the web to find a solution but I couldn’t find one, is there a way to get the word before the caret position in an editable div so a bit like:
JavaScript
x
2
1
This is some| demo texts
2
This should return the word “some”… I don’t know if this is possible, I would be glad for any help, thanks :).
Advertisement
Answer
With using Caret Position finder method provided here this will do what you want.
JavaScript
1
35
35
1
function ReturnWord(text, caretPos) {
2
var index = text.indexOf(caretPos);
3
var preText = text.substring(0, caretPos);
4
if (preText.indexOf(" ") > 0) {
5
var words = preText.split(" ");
6
return words[words.length - 1]; //return last word
7
}
8
else {
9
return preText;
10
}
11
}
12
13
function AlertPrevWord() {
14
var text = document.getElementById("textArea");
15
var caretPos = GetCaretPosition(text)
16
var word = ReturnWord(text.value, caretPos);
17
if (word != null) {
18
alert(word);
19
}
20
21
}
22
23
function GetCaretPosition(ctrl) {
24
var CaretPos = 0; // IE Support
25
if (document.selection) {
26
ctrl.focus();
27
var Sel = document.selection.createRange();
28
Sel.moveStart('character', -ctrl.value.length);
29
CaretPos = Sel.text.length;
30
}
31
// Firefox support
32
else if (ctrl.selectionStart || ctrl.selectionStart == '0')
33
CaretPos = ctrl.selectionStart;
34
return (CaretPos);
35
}
JavaScript
1
3
1
<input id="textArea" type="text" />
2
<br />
3
<input id="Submit" type="submit" value="Test" onclick="AlertPrevWord()" />
Here is also a jsfiddle.