Chelseawillrecover
Chelseawillrecover

Reputation: 2644

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

Upvotes: 3

Views: 1452

Answers (2)

dfsq
dfsq

Reputation: 193261

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/

Upvotes: 2

falsetru
falsetru

Reputation: 369164

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/

Upvotes: 2

Related Questions