How to count the number of characters in a string using JavaScript

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

+4
source share
3 answers

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 
+3
source

Actually, I want to trim the text inside the div so that it exactly matches that div (the length of the text is very long)

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/

+4
source

You can only calculate the number of characters per line if the width of each character is the same. This is true for all fixed-width fonts, such as in the stackoverflow question editor.

If you use a font with a fixed width, you can calculate the width of one character, for example. using the function posted in this answer . Then just divide the width of the <div> by the width of the character.

+1
source

Source: https://habr.com/ru/post/1381019/


All Articles