Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Measuring length of string in pixel in javascript

Tags:

javascript

How do I find the length of string in pixels in javascript , if I know the font-size and font-family?

like image 863
KK123 Avatar asked May 10 '13 09:05

KK123


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.

Can you call the length of a string in 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.

Is string length a function or a property JavaScript?

Length is not a method, it is a property. It doesn't actually do anything but return the length of an array, a string, or the number of parameters expected by a function. When you use . length, you are just asking the JavaScript interpreter to return a variable stored within an object; you are not calling a method.


2 Answers

The simplest solution is to create an in memory canvas (i.e. one that isn't added to the DOM) and then use the measureText function :

var canvas = document.createElement('canvas');
var ctx = canvas.getContext("2d");
ctx.font = "11px Arial";        
var width = ctx.measureText(str).width;
like image 166
Denys Séguret Avatar answered Nov 13 '22 14:11

Denys Séguret


you can put your string into paragraph and use the jquery width function to get the width in pixel width

    function showWidth(ele, w) {
$("div").text("The width for the " + ele +
" is " + w + "px.");
}
$("#getp").click(function () {
showWidth("paragraph", $("p").width());
});

check jsfiddle

like image 21
Ganesh Bora Avatar answered Nov 13 '22 14:11

Ganesh Bora