Sometimes, we want to count the number of lines of a string in JavaScript.
In this article, we’ll look at how to count the number of lines of a string in JavaScript.
How to count the number of lines of a string in JavaScript?
To count the number of lines of a string in JavaScript, we can use the string split
method.
For instance, we write
const lines = str.split(/\r\n|\r|\n/);
to call str.split
with a regex that matches all line breaks in the str
string to split the string by the new line characters.
It returns an array of split substrings so we can use the length
property of the lines
array to get the number of lines in str
.
Conclusion
To count the number of lines of a string in JavaScript, we can use the string split
method.