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

后端 未结 2 1919
孤城傲影
孤城傲影 2020-12-21 13:09

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 every

2条回答
  •  [愿得一人]
    2020-12-21 13:43

    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.

提交回复
热议问题