I have a textarea with this content:
<textarea id="text">
Hello! Who am I? This is the third sentence. This, is another sentence.
</textarea>
Since it's a textarea, it can be focused. I'm trying to find a way to:
Separate all sentences inside the textarea into a javascript array. I tried a $('#text').val().split() approach, but there is more than just one sentence separator in my example.
I also need to know in which sentence the cursor is currently positioned on.
Why, you may ask? I need to process (with a paid API that charges per character) sentences when the user changes their content. If I only make a small change in the 2nd sentence, why should the 1st, 3rd and 4th sentences be submitted? It is of course much less expensive to only submit the 2nd one.
As I previously said, the .split() approach would be perfect if people only used dots to separate sentences, but there are other characters that should also be considered (!?.) -- about the second point, i found a function to find de caret position:
function doGetCaretPosition (ctrl) {
var CaretPos = 0;
if (document.selection) {
ctrl.focus ();
var Sel = document.selection.createRange ();
Sel.moveStart ('character', -ctrl.value.length);
CaretPos = Sel.text.length;
} else if (ctrl.selectionStart || ctrl.selectionStart == '0') {
CaretPos = ctrl.selectionStart;
}
return (CaretPos);
}
The question is, how does the position help me find the sentence number? All ideas are welcome!