vjjj vjjj - 5 months ago 23x
Javascript Question

Textarea - get each line, find line breaks

I want to get each line in a textarea. The textarea is small and wraps words according to width constraints. So I tried:

// Sample text: I want to find(line wrapped) all lines here

// 1, not the right length, should be 2

// 1

// 1

// 1

I also tried
white-space: pre-wrap
individually and together.

Nothing seems to find line-breaks!! Need help, thanks.


So the way I did it was:

  • Clone the textarea in question - $("#text") into a transparent textarea. Use transparent font.
  • Change id value of clone to, say, $("#newtext") and append it to DOM.
  • On every keyup, we take the value of $("#text") before this character's keyup. Put that value into $("#newtext") and check if $("#newtext").get(0).scrollHeight() > $("#newtext").height(). If true => this character caused a line break.
  • Increase rows of $("#newtext") in a loop until
    $("#newtext").get(0).scrollHeight() === $("#newtext").height()
  • Take text before this character, add a \n, add this character to $("#newtext").val()
  • Apply $("#newtext").val() to $("#text").val().
  • Remove $("#newtext") from DOM.
  • Repeat all of above steps on every keyup event

Above answer works on similar lines as - stackoverflow.com/questions/3738490/finding-line-wraps – evolutionxbox yesterday

So, basically we convert line breaks into newlines which can be found by using $("#text").val().split("\n").

(Note - If we don't append transparent textarea to the DOM, its scrollHeight() will be undefined)