Posted By

kouphax on 11/13/08


Tagged

javascriptstringfitwidth


Versions (?)

Who likes this?

2 people have marked this snippet as a favorite

ginoplusio
VaiT


Fit String to Width


 / Published in: JavaScript
 

URL: http://stackoverflow.com/questions/282758/truncate-a-string-nicely-to-fit-within-a-given-pixel-width

Examine a string and truncate it so that it fits into the required width based on font-size/weight etc

  1. function fitStringToWidth(str,width,className) {
  2. // str A string where html-entities are allowed but no tags.
  3. // width The maximum allowed width in pixels
  4. // className A CSS class name with the desired font-name and font-size. (optional)
  5. // ----
  6. // _escTag is a helper to escape 'less than' and 'greater than'
  7. function _escTag(s){ return s.replace("<","&lt;").replace(">","&gt;");}
  8.  
  9. //Create a span element that will be used to get the width
  10. var span = document.createElement("span");
  11. //Allow a classname to be set to get the right font-size.
  12. if (className) span.className=className;
  13. span.style.display='inline';
  14. span.style.visibility = 'hidden';
  15. span.style.padding = '0px';
  16. document.body.appendChild(span);
  17.  
  18. var result = _escTag(str); // default to the whole string
  19. span.innerHTML = result;
  20. // Check if the string will fit in the allowed width. NOTE: if the width
  21. // can't be determinated (offsetWidth==0) the whole string will be returned.
  22. if (span.offsetWidth > width) {
  23. var posStart = 0, posMid, posEnd = str.length, posLength;
  24. // Calculate (posEnd - posStart) integer division by 2 and
  25. // assign it to posLength. Repeat until posLength is zero.
  26. while (posLength = (posEnd - posStart) >> 1) {
  27. posMid = posStart + posLength;
  28. //Get the string from the begining up to posMid;
  29. span.innerHTML = _escTag(str.substring(0,posMid)) + '&hellip;';
  30.  
  31. // Check if the current width is too wide (set new end)
  32. // or too narrow (set new start)
  33. if ( span.offsetWidth > width ) posEnd = posMid; else posStart=posMid;
  34. }
  35.  
  36. result = '<abbr title="' +
  37. str.replace("\"","&quot;") + '">' +
  38. _escTag(str.substring(0,posStart)) +
  39. '&hellip;<\/abbr>';
  40. }
  41. document.body.removeChild(span);
  42. return result;
  43. }

Report this snippet  

You need to login to post a comment.