How to find the number of lines in an HTML text area with JavaScript?

Sometimes, we want to find the number of lines in an HTML text area with JavaScript.

In this article, we’ll look at how to find the number of lines in an HTML text area with JavaScript.

How to find the number of lines in an HTML text area with JavaScript?

To find the number of lines in an HTML text area with JavaScript, we can call the match method on the input value.

For instance, we write:

<textarea></textarea>

to add a text area.

Then we write:

const textarea = document.querySelector('textarea')
textarea.onchange = (e) => {
  console.log(e.target.value.match(/n/g).length + 1)
}

to select the text area with querySelector.

Then we set textarea.onchange to a function that takes the input value from e.target.value.

Then we call match on it with the line break regex to find the number of line breaks.

And finally, we add 1 to that to get the number of lines.

Conclusion

To find the number of lines in an HTML text area with JavaScript, we can call the match method on the input value.