Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count number of Paragraphs excluding spaces

I am currently working on a code to count the number of paragraphs. The only issue I have not been able to resolve is that spaces inbetween each paragraphs is also been counted. For instance, below example should return 3 but rather it returns 5 because of the empty carriage returns.

sentence 123
sentence 234


sentence 345

Full Fiddle

Is there a regex combination that can resolve this or must I write a conditional statement. Thanks

like image 661
Chelseawillrecover Avatar asked Dec 11 '25 06:12

Chelseawillrecover


2 Answers

Exclude blank lines explicitly:

function nonblank(line) {
    return ! /^\s*$/.test(line);
}

.. the_result_of_the_split.filter(nonblank).length ..

Modified fiddle: http://jsfiddle.net/Qq38a/

like image 74
falsetru Avatar answered Dec 13 '25 19:12

falsetru


You can change your regexp a liitle:

.split(/[\r\n]+/)

+ character in regexp

matches the preceding character 1 or more times. Equivalent to {1,}.

Demo: http://jsfiddle.net/ahRHC/1/

UPD

Improved solution would use another regexp using negative lookahead:

`/[\r\n]+(?!\s*$)/` 

This means: match new lines and carriage returns only if they are not followed by any number of white space characters and the end of line.

Demo 2: http://jsfiddle.net/ahRHC/2/

UPD 2 Final

To prevent regexp from becoming too complicated and solve the problem of leading new lines, there is another solution using $.trim before splitting a value:

function counter(field) {
    var val = $.trim($(field).val());
    var lineCount = val ? val.split(/[\r\n]+/).length : 0;
    jQuery('.paraCount').text(lineCount);
}

Demo 3: http://jsfiddle.net/ahRHC/3/

like image 44
dfsq Avatar answered Dec 13 '25 21:12

dfsq



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!