Get string length in pixels using JavaScript

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

In the enlarged image, I am trying to determine how many spaces would be needed to fill this line length. As you can probably say above, I think that the best option would be to simply measure the length of the string and one space from the user's point of view and calculate how many spaces the text based on this should replace. This will appear in the HTML input text, by the way.

Thanks.

+2
source share
2 answers

You can determine the number of pixels in a row container. You can do this by creating a hidden element in the DOM, setting the internal HTML to a string and then requesting the width.

+2
source

I do not think this is a good and easy way to do this, except for calculating the length of the container. The width depends on the font size, font, the distance between the letters, it will differ depending on the browser, etc.

+2
source

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


All Articles