May 27, 2012
How can I replace part of a string which is wider than 50 px with "…"?
Question by Snehal Kumar Mishra
I am looking for a function which replaces part of a string which is wider than 50px with "..."
. I want to implement it in Javascript/jQuery.
Example:
- Say I have a variable
var="Theta Saving Non-Qualified Plan";
I want to put a restriction on the length of the string (based on pixel width). If the length of string is more that 50px, then the part of the string which is from the 51st pixel to theend of string will be replaced with"..."
.
Any idea guys?
Answer by Starx
This cannot be deduced as easy as you would like it to be. Because how much width a character or set of characters will take will depend upon the font-size. And calculating a text width is hardly accurate.
So, its better you create your interface to be friendly with characters rather than the width.
var t = $("#div").text();
if(t.length > 50) {
$("#div").text(t.substr(0,50)+"...");
}