4

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?

Tats_innit
  • 33,991
  • 10
  • 71
  • 77
  • Look at this thread: http://stackoverflow.com/questions/118241/calculate-text-width-with-javascript – Afshin Mehrabani May 27 '12 at 06:42
  • 1
    jQuery text width calculation: http://stackoverflow.com/questions/1582534/calculating-text-width-with-jquery (not an exapt duplicate though, as it only calculates and doesn't update the text). – Anders Abel May 27 '12 at 06:43

5 Answers5

2

Don't try to reinvent the wheel. Use a Jquery plugin like this: http://tpgblog.com/2009/12/21/threedots-the-jquery-ellipsis-plugin/

Mandar Limaye
  • 1,900
  • 16
  • 24
1

Here's a solution if you want to truncate the visual and don't really need to truncate the actual string:

<p>
  <span style='width: 50px; height: 1em; 
        overflow: hidden; display: inline-block'>
  This is the long string which should appear truncated followed by elipses
  </span>
  <span>...</span>
</p>

To make it work in IE6 and 7, I think you need to add the following CSS:

zoom: 1
*display: inline;
Kayo
  • 966
  • 1
  • 7
  • 16
0

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)+"...");
} 
Starx
  • 77,474
  • 47
  • 185
  • 261
0

I would split the string in an array, then add letter after letter testing the width of the element to know if it's lower than 50px

ie :

var vElement = $('.your_element');

var vStr = vElement.html();

var vShortStr = "";

var vArray = vStr.split("");

for (var i=0; i<vArray.length; i++){

vShortStr += vArray[i];

vElement.html(vShortStr);

if(vElement.width() > 50){

    vShortStr = vShortStr.substring(0, vShortStr.length-1);

    vShortStr += "...";

    vElement.html(vShortStr);

    break;

    }

}
​
laurent
  • 505
  • 7
  • 16
0

If your text is already enclosed in a block element with 50px width, you can use the text-overflow CSS rule, which is widely supported by virtually all browsers. Also see text-overflow at quirksmode.

lanzz
  • 42,060
  • 10
  • 89
  • 98