Reputation: 2644
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
Is there a regex combination that can resolve this or must I write a conditional statement. Thanks
Upvotes: 3
Views: 1452
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,}.
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.
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);
}
Upvotes: 2
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