The contents of a textarea are stored in its value property. Here, new lines are represented by the ASCII new line non-printing character \n. We can split apart the the value of the textarea to give us an array which contains each line.
Next, we make another array, which will contain the starting positions of each line. We add 0 as an implied value. Next, we loop through the entire text array (starting from the second line as we have already added the first), and each time add an element to the lines array which is the lines array value for the text item before this one and the length of the text item before this one.
The logic in this is that:
- The
lines array contains all of the previous starting positions
- The length of the previous
text item added to the previous lines item results in (in your examples) something such as 0 + "this is test1".length = 13, which of course is one off.
- So, we add one, yielding
0 + "this is test1".length + 1 = 14, and 14 + "and this is test2".length + 1 = 32.
Then, we simply test that pos (the position that we want to check; passed to the function) is in the lines array. If it is, then the result is true, else it's false.
Javascript Code:
function testpos(pos) {
var text = document.getElementById("textareaid").value.split("\n");
var lines = [0];
for (i=1;i<text.length;i++) {
lines.push(lines[i-1]+text[i-1].length+1)
}
return lines.indexOf(parseInt(pos))!=-1
}
You'll need this as your HTML:
<textarea id="textareaid">this is test1
and this is test2
plus it is test3</textarea>
And, here's a live demo: https://jsfiddle.net/g562gtge/