Update: Oh, I forgot a hidden comment. The CSS solution posted above is definitely better suited to work. My answer directly addresses the issue of counting characters that match a single line. I am not going to delete it, as someone might find it useful.
You can definitely get the number of characters that you can put on one line, even if you have a proportional font. There are two ways: either use the following trick, or the measureText CanvasRenderingContext2D method.
var target_width = 200; // line width var text = 'Lorem ipsum. I want to know how many chars of this text fit.'; var span = document.createElement('span'); document.body.appendChild(span); span.style.whiteSpace = 'nowrap'; // define the style span.style.fontFamily = 'Lucida Grande'; span.style.fontSize = '14px'; var fit = text.length; for (var i = 0; i < fit; ++i) { span.innerHTML += text[i]; if (span.clientWidth > target_width) { fit = i - 1; break; } } document.body.removeChild(span); // fit = the number of characters of the text // that you can fit on one line
source share