如何将光标位置作为最后一行的文本区域的值拆分
How to split the value of a textarea with the cursor position as the last line
我想用 \n
拆分文本区域的值,并将光标所在的行作为数组中的最后一个值例如:
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
现在数字是textarea中的行,第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').prop("selectionStart");
和
$('#theTextArea').prop("selectionEnd");
以上属性为您提供了光标在现代浏览器上的位置。这个问题已经 linked here before though。对于旧版浏览器,这可能会有问题。
但是给定光标位置,您应该能够将子字符串抓取到光标索引。然后使用正则表达式获取最后一行的内容到字符串的末尾。
您可以通过 jQuery
substr()
来实现。
你selecttextarea值的子串从起点到光标所在的点,用换行符分割。像这样;
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];
我想用 \n
拆分文本区域的值,并将光标所在的行作为数组中的最后一个值例如:
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
现在数字是textarea中的行,第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').prop("selectionStart");
和
$('#theTextArea').prop("selectionEnd");
以上属性为您提供了光标在现代浏览器上的位置。这个问题已经 linked here before though。对于旧版浏览器,这可能会有问题。
但是给定光标位置,您应该能够将子字符串抓取到光标索引。然后使用正则表达式获取最后一行的内容到字符串的末尾。
您可以通过 jQuery
substr()
来实现。
你selecttextarea值的子串从起点到光标所在的点,用换行符分割。像这样;
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];