Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
469 views
in Technique[技术] by (71.8m points)

jquery - How to count number of characters in a line using JavaScript

Suppose I have a div with width 200px and font-size 16. Now I want to calculate number of characters that can be fit into a line of div. How can I calculate number of character using JavaScript or jQuery.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Update: Oh, I overlooked the hidden comment. The CSS solution posted above is definitely better for the job. My answer addresses directly the problem of counting the characters that fit on one line. I'm not going to delete it as someone might actually find it useful.

It is definitely possible to get the number of characters you can fit on one line even if you have a proportional typeface. There are two ways—either use the following trick or the measureText method of CanvasRenderingContext2D.

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...