Search code examples
javascriptstringtextpixel

Get string length in pixels with JavaScript


Let's say I have the string "Hello". This string is obviously five characters in length, but what is its length in pixels? Is there an easy way to determine this length in JavaScript? I have thought of a solution where an extra div would have to be displayed to the user, but this way seems hacky and complicated.

In the bigger picture, I am trying to determine how many spaces would be necessary to fill that length of the string. As you can probably tell from above, I think the best option would be to simply measure the length of the string and a single space character from the user's perspective and calculate how many spaces should replace the text based off of that. This is going to be displayed in an HTML input text, by the way.

Thanks.


Solution

  • You can determine the number of pixels the container of the string. You can do this by creating a hidden element in the DOM, setting the inner HTML to the string and then asking for the width.