Javascript 如何将光标位置作为最后一行拆分textarea的值

Javascript 如何将光标位置作为最后一行拆分textarea的值,javascript,jquery,textarea,Javascript,Jquery,Textarea,我想用\n拆分textarea的值,并将光标所在的行作为数组中的最后一个值,例如: 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 现在,数字是文本区域中的行,第4行是光标所在的行。所以我想分割这些行,忽略第5行和第6行,将第4行作

我想用\n拆分textarea的值,并将光标所在的行作为数组中的最后一个值,例如:

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
现在,数字是文本区域中的行,第4行是光标所在的行。所以我想分割这些行,忽略第5行和第6行,将第4行作为最后一行。然后我将运行如下代码:

lastLine = //the position of the cursor
if(lastLine == ""){
    console.log('empty');
} else {
    //get the value of the previous line before the lastLine
}
请问我如何使用jQuery或JavaScript实现这一点

$'theTextArea'。propselectionStart; 及

$'theTextArea'。按比例选择结束

上面的属性为您提供了光标在现代浏览器上的位置。这个问题已经解决了。对于较旧的浏览器,这可能会有问题


但是给定光标位置,您应该能够抓住光标索引的子字符串。然后使用正则表达式获取字符串末尾最后一行的内容。

您可以通过jQuery substr实现这一点

从起始点到光标所在点,选择textarea值的子字符串,并用换行符将其拆分。像这样,

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];

你试过什么?