You must remember that before calculating the pixel width of a string in relation to this character account, you need to somehow know the metrics of the font used.
If then you had to take the input string, wrap it in <span>, paste it into the document, calculate the width of the element, and then remove the range and add the value to the final destination, which you will have a pretty decent projection of the estimated width, while your range has the same font style rules as the destination element.
If you want to get really fantasy and technical information about this, then the HTML 5 <canvas> tag is your friend.
A good article to better understand the complexity of font metrics in javascript, which will also help you solve this problem: http://mudcu.be/journal/2011/01/html5-typographic-metrics/#measure
source share