Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get string length in pixels using JavaScript [duplicate]

I want to know exact length in pixels of String i.e. "Hello World".

It should not be length of my container.

Any Help???

like image 618
Kundan Atre Avatar asked Feb 13 '13 11:02

Kundan Atre


People also ask

How do you find the length of a string in pixels?

By their nature, strings do not have lengths in in pixels or something like that. Strings are data structures totally abstracted from the way they are presented, such as fonts, colors, rendering styles, geometrical sizes, etc. Those are all some properties of some UI elements, whatever they are.

How do you find the length of a string in JavaScript?

The length property returns the length of a string. The length property of an empty string is 0.

Does .length work on strings JavaScript?

The length of a string in JavaScript can be found using the . length property. Since . length is a property it must be called through an instance of a string class.

Which of the following property is useful for finding length of string in JS?

The length read-only property of a string contains the length of the string in UTF-16 code units.


1 Answers

You can create some inline element (span, for example), set your string as element's content (innerHTML), insert it into document (append to some element) and get it's width (clientWidth).

There is no other way to measure length of string in pixels because it depends on font style.

like image 175
Artem Sobolev Avatar answered Oct 28 '22 13:10

Artem Sobolev