Reputation: 1001
I am trying to find number of lines in a div like this jsfiddle, but instead of returning 5 it is giving me 9. Any idea what is wrong here
var lines = document.getElementById('ptest').textContent;
alert(lines.split(/\r\n|\r|\n/).length);
P.S. - I also want to use the code to read the num of lines in a paragraph
Upvotes: 0
Views: 180
Reputation: 4615
try filter(String)
to remove empty arrays
var len=document.getElementById('ptest').textContent.split(/\n/).filter(function(a){ var b = a.replace(/ /g,''); return (typeof(b) == 'string' && b != '')}).length
alert(len)
Upvotes: 1
Reputation: 24
You may have some extra new line character after opening div or before closing div.
<div>
asd asda sdf
asd
sdsa sada</div>
will give you 5 output.
while
<div>asd asda sdf
asd
sdsa sada</div>
will give you correct output as 3
Upvotes: 0