Categories
JavaScript Answers

How to Get the Number of Lines in a textarea Using JavaScript?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

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

Leave a Reply

Your email address will not be published. Required fields are marked *