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)+"...");
} 

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!