Find out the 'line' (row) number of the cursor in a textarea

后端 未结 3 1105
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-01 09:13

I would like to find out and keep track of the \'line number\' (rows) of the cursor in a textarea. (The \'bigger picture\' is to parse the text on the line every time a new

3条回答
  •  無奈伤痛
    2020-12-01 09:59

    This worked for me:

    function getLineNumber(textarea) {
      return textarea.value.substr(0, textarea.selectionStart) // get the substring of the textarea's value up to the cursor position
        .split("\n") // split on explicit line breaks
        .map((line) => 1 + Math.floor(line.length / textarea.cols)) // count the number of line wraps for each split and add 1 for the explicit line break
        .reduce((a, b) => a + b, 0); // add all of these together
    };
    

    Inspired by colab's answer as a starting point, this includes the number of word wraps without having to introduce a mirror (as in bradbarbin's answer).

    The trick is simply counting how many times the number of columns textarea.cols can divide the length of each segment between explicit line breaks \n.

    Note: this starts counting at 1.

提交回复
热议问题