- Instant help with your JavaScript coding problems

Count the number of lines in a string in JavaScript

Question:
How to count the number of lines in a string using JavaScript?
Answer:
const getLineCount = (text) => {
    if (!text) {
        return 0;
    }
    
    return text.split(/\n/).length;
}
Description:

The split() method divides a string into a list of substrings, puts these substrings into an array, and returns the array. The division is done by searching for a pattern (separator); where the pattern is provided as the first parameter in the method's call. The separator can be a simple string or it can be a regular expression.

To get the line numbers in a string, count the number of newline characters. 

Reference:
Split reference
Share "How to count the number of lines in a string using JavaScript?"
Related snippets:
Tags:
lines, string, count, javascript, number of lines, string lines
Technical term:
Count the number of lines in a string