Dylan Dylan - 5 months ago 15
Javascript Question

JavaScript textarea get numbers of lines (with linebreaks)

I have a textarea and I want to know how many lines there are. Now I have searched but I only see this solution:

mytextarea.value.split("\n").length


Well, that works but that's not what I want.

For example my textarea is like this:

textarea

When I type this:

123456789abcdefghijkl
sasasasakasasask;as


When I use split("\n").value I get 2 which is correct but if I put this in:

123456789abcdefghijklsasasasasasasasasas


I get the result 1 which isn't correct:

textarea without enters

The result should be 2 because there are 2 lines however the line breaks are not created with
\n
.

Anyone an idea how you can calculate the number of lines INCLUDING the line breaks without
\n
?

Answer

Got it!

static lineCaculator() {
            let dummy               = document.createElement('div');
            dummy.style.font        = AutoTextareaResizer.computedStyle.call(this, 'font');
            dummy.style.width       = AutoTextareaResizer.computedStyle.call(this, 'width');
            dummy.style.wordWrap    = 'break-word';
            dummy.innerHTML         = this.value;


            document.body.appendChild(dummy);

            let lines = parseInt(AutoTextareaResizer.computedStyle.call(dummy, 'height')) /  this.realLineHeight;

            document.body.removeChild(dummy);

            return Math.max(1, lines);
        }