How do I find the length of string in pixels in javascript , if I know the font-size and font-family?
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.
The length property returns the length of a string. The length property of an empty string is 0.
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.
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.
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;
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With