Get the Number of Lines in a textarea Using JavaScript
To get the number of lines in a textarea using JavaScript, we can call split
on the input value of the textarea by the newline character.
Then we get the length
of the returned string array.
For instance, we can write:
<textarea></textarea>
to create a textarea element.
Then we write:
const textarea = document.querySelector('textarea')
textarea.addEventListener('input', () => {
const text = textarea.value;
const lines = text.split("\n");
const count = lines.length;
console.log(count);
})
We select the textarea with the document.querySelector
.
Then we call addEventListener
to listen to the input
event.
In the input event handler, we get the textarea’s input value with textarea.value
.
Then we call split
with \n
to split the value by the newline character.
And finally, we get the length
of the split lines.
Therefore, now we should see the number of lines logged as we type.
4 replies on “How to Get the Number of Lines in a textarea Using JavaScript?”
Hallo John
Thank you for your explaination.
However, I do a problem …
When the lines written are longer – and continue on next line(s) – than the text areas width, then it doesn’t work.
Do you have any idea how to get the exact number of lines in this case.
Thanks in advance.
Kåre
Hi Kåre,
Thanks for reading. There’s no way to determine the number of lines exactly.
There’re complex solutions like this one https://stackoverflow.com/a/45252226 you can try.
Thank you for the hint. It worked correctly.
No problem