Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 467
Anoop Avatar asked Nov 13 '11 19:11

Anoop


People also ask

How do I count the number of lines in JavaScript?

To count the number of lines of a string in JavaScript, we can use the string split method. const lines = str. split(/\r\n|\r|\n/);


3 Answers

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
like image 191
J. K. Avatar answered Sep 29 '22 05:09

J. K.


Actually I want to truncate my text inside div so that it exactly fit into that div( text length is very large)

You can do this with css:

white-space: nowrap;
overflow:hidden;
text-overflow: ellipsis; //Doesn't work in all browsers, just adds "..."

http://jsfiddle.net/46AML/

like image 22
Esailija Avatar answered Sep 29 '22 03:09

Esailija


You can only calculate the numbers of characters per line if the width of each character is the same. This is true for all fixed-width fonts like the one in the question editor of stackoverflow.

If you ensured using a fixed-width font, you can calculate the width of a single character, e.g. using the function posted in this answer. Then, simply divide the width of the <div> through the width of a character.

like image 36
Yogu Avatar answered Sep 29 '22 05:09

Yogu