2

I want to split the value of a textarea with \n and make the line where the cursor is positioned as the last value in the array for example:

1. fyg tgiyu rctvyu cuiby cutv cutrvyb crtvyb
2. rutyu rtcvyb ctrvybu ctrvybu rtcvy
3. rutiyu crtvyu crtvyb rtvyb
4. |
5. tgyho8uji vtybui
6. tvybui yivtubi

Now the numbers are the lines in the textarea and line 4 is the line where the cursor is positioned. so I want to split the lines ignoring line 5 and 6 have line 4 as the last line. Then I will run a code like this:

lastLine = //the position of the cursor
if(lastLine == ""){
    console.log('empty');
} else {
    //get the value of the previous line before the lastLine
}

Please how do I achieve this using jQuery or JavaScript

2 Answers2

0

$('#theTextArea').prop("selectionStart"); and

$('#theTextArea').prop("selectionEnd");

The above properties give you the location of the cursor on modern browsers. This question has been linked here before though. For older browsers it could be problematic.

But given the cursor position you should be able to just grab the substring to the cursor index. Then use a regex to get the contents of the last line to the end of the string.

Community
  • 1
  • 1
Scott Fanetti
  • 126
  • 1
  • 5
0

You can achieve this by the jQuery substr().

You select the substring of the textarea value from the starting point to the point where the cursor is located and split it with line breaks. Like this;

value = $('textarea').val();
// to get the position of the cursor
index = $('textarea').prop('selectionstart');
// select all from the starting point to the cursor position ignoring line 5 and 6
str = value.substr(0, index);
// split the str with a line break
splt = str.split('\n');
// then finally to get your last line
lastLine = splt[splt.length - 1];
KANAYO AUGUSTIN UG
  • 2,078
  • 3
  • 17
  • 31