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!
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With