madhur madhur - 2 months ago 8
Javascript Question

Getting number of lines in a div

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

Answer

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)
Comments