Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to count empty lines inside a string in javascript

I'm trying to count all the empty lines inside a string. My current function kind of works:

function count_empty(text) {
    var regex = /\r\n?|\n/g;
    var lines = text.split(regex);
    var sep = [];
    $.each(lines, function(k, val) {
        if(!val) {
            //sentence
            sep.push(val);
        }
    });
    return sep.length;
}

...but I really think it could be achieved with a far better approach with something like this:

function count_empty(text) {
    return (text.match(/\r\n?|\n/g) || []).length;
}

Of course, the regex in the 2nd alternative should be retouched to actually accomplish the requirements. So, the question is: What regex should I use in the second approach to retrieve the blank lines only?

One consideration: If a line contains whitespaces only, it will be treated as an empty line.

This textarea's string should return 3 with the function.

<textarea id="test">first line

third line


</textarea>

Thanks!

like image 691
Andres SK Avatar asked Jul 27 '26 13:07

Andres SK


1 Answers

If you enable multi-line mode, m, for your regular expressions, you can match empty lines, ^$, and count how many matches have been found. Note that [ \t]* will match zero or more spaces or tabs.

function count_lines(text){
    return text ? (text.match(/^[ \t]*$/gm) || []).length : 0;
}

This should be really fast since no post-processing after the regular expression is necessary.

See Regex101 for a demo with annotations.

like image 160
Gio Borje Avatar answered Jul 30 '26 01:07

Gio Borje



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!