Find value of current line of a <textarea> using javascript

吃可爱长大的小学妹 提交于 2019-12-18 09:16:18

问题


How can I find the value of the current line of a textarea?

I know I have to find the caret position, but then find everything before it up to the last \n and everything after it to the next \n.

How can I do this?


回答1:


A simple way would be to just loop:

var caretPos = 53, // however you get it
    start, end
;

for (start = caretPos; start >= 0 && myString[start] != "\n"; --start);
for (end = caretPos; end < myString.length && myString[end] != "\n"; ++end);

var line = myString.substring(start + 1, end - 1);



回答2:


In line with nickf's answer, the following example (which uses jQuery) may be a bit faster because it uses (lastI|i)ndexOf:

function current_line(textarea) {
  var $ta = $(textarea),
      pos = $ta.getSelection().start, // fieldselection jQuery plugin
      taval = $ta.val(),
      start = taval.lastIndexOf('\n', pos - 1) + 1,
      end = taval.indexOf('\n', pos);

  if (end == -1) {
      end = taval.length;
  }

  return taval.substr(start, end - start);
}

Here it is on jFiddle.



来源:https://stackoverflow.com/questions/3153995/find-value-of-current-line-of-a-textarea-using-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!