2

i'm using this function to count empty lines inside a string.

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

I'm trying to edit that regex in order to implement a function that counts non empty lines.

function count_non_empty_lines(text){
}

Any ideas? Thanks!

0

2 Answers 2

10

text = ["  a", "b", "", "c", "", "", "   d  "].join("\n")

cnt = (text.match(/^\s*\S/gm) || "").length
alert(cnt)

Sign up to request clarification or add additional context in comments.

1 Comment

Why a simple ^.*?\S will do the job. Note that \s matches newline characters also.
0

You could simply .split("\n").length to get the number of all lines and subtract your existing result from that:

function count_non_empty_lines(text){
    return text.split("\n").length - count_empty_lines(text);
}

3 Comments

of course, but that would not be the most efficient way to achieve that.
No, but it is the simplest
Since I'll be processing lots of strings I need the most efficient and fast way to retrieve the data. @georg 's answer seems to be the best approach. Thanks anyways!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.