Counting Valid Lines in a Textarea with JavaScript

I recently had a requirement to count the number of valid (non-empty) lines in a textarea on a page, limit the total number of lines, and display the remaining available lines. [Besides counting lines, you could also check for spaces, commas, semicolons, etc. – the approach is similar.]

My initial idea was: Write a regex to replace multiple consecutive newlines “\n” with a single “\n”: str.replace(/\n+/, "\n"); But this doesn’t handle cases where there are multiple empty lines with leading spaces.

Later: Simply split by “\n”, then count entries with length greater than 0 as valid lines.

Here’s the code:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
<script type="text/javascript">
var maxTagCount = 100;
function checkLine(textArea) {
    var str = textArea.value;
    var lines = str.split('\n');
    var countLine = 0;
    for (var i = 0; i < lines.length; i++) {
        if (lines[i].length > 0) {
            countLine++;
        }
    }
    var tagElement = document.getElementById("tagTextarea");
    
    if (countLine > maxTagCount) {
        var varNewValue = "";
        var index = 0;
        for (var i = 0; i < lines.length; i++) {
            if (index >= maxTagCount) {
                break;
            }
            if (lines[i].length > 0) {
                index++;
            }
            varNewValue += lines[i];
            varNewValue += "\n";
        }
        textArea.value = varNewValue;
        stat_left.innerHTML = 0;
    } else {
        stat_left.innerHTML = maxTagCount - countLine;
    }
}
</script>

Web demo: countLines