Shafizadeh
Shafizadeh

Reputation: 10340

How do I detect whether a position is at the beginning of a line in a textarea?

I have a textarea like this:

<textarea>
this is test1
and this is test2
plus it is test3
</textarea>

As you see, this positions are in the beginning of line: 0 (t), 14 (a), 32 (p).


Now I need to determine whether a position (I mean is the number of position) is at the beginning of a line?

For example:

10 : false
5  : false
14 : true
40 : false

How can I do that?

Upvotes: 2

Views: 505

Answers (3)

toastrackengima
toastrackengima

Reputation: 8732

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/

Upvotes: 3

Mi-Creativity
Mi-Creativity

Reputation: 9654

JS Fiddle

var ta = document.getElementById('ta1'),
  taText = ta.textContent;

var lines = taText.trim().split('\n');

for (var i in lines) {
  console.log(lines[i][0]);
}
<textarea id="ta1">
this is test1
and this is test2
plus it is test3
</textarea>

Upvotes: 1

Gavriel
Gavriel

Reputation: 19237

if you want to know that the n-th position is at the beginning, then:

n == 0 || $("#textbox").val()[n-1] == '\n'

Upvotes: 1

Related Questions