Sometimes, we want to get the number of lines in a textarea using JavaScript.
In this article, we’ll look at how to get the number of lines in a textarea using JavaScript.
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.
Conclusion
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.