truncate text with javascript


/ Published in: Other
Save to your folder(s)



Copy this code and paste it in your HTML
  1. <p id="truncateMe">Lorem ipsum dolor sit amet, consectetuer adipiscing
  2. elit. Aenean consectetuer. Etiam venenatis. Sed ultricies, pede sit
  3. amet aliquet lobortis, nisi ante sagittis sapien, in rhoncus lectus
  4. mauris quis massa. Integer porttitor, mi sit amet viverra faucibus,
  5. urna libero viverra nibh, sed dictum nisi mi et diam. Nulla nunc eros,
  6. convallis sed, varius ac, commodo et, magna. Proin vel
  7. risus. Vestibulum eu urna. Maecenas lobortis, pede ac dictum pulvinar,
  8. nibh ante vestibulum tortor, eget fermentum urna ipsum ac neque. Nam
  9. urna nulla, mollis blandit, pretium id, tristique vitae, neque. Etiam
  10. id tellus. Sed pharetra enim non nisl.</p>
  11.  
  12. <script type="text/javascript">
  13.  
  14. var len = 100;
  15. var p = document.getElementById('truncateMe');
  16. if (p) {
  17.  
  18. var trunc = p.innerHTML;
  19. if (trunc.length > len) {
  20.  
  21. /* Truncate the content of the P, then go back to the end of the
  22. previous word to ensure that we don't truncate in the middle of
  23. a word */
  24. trunc = trunc.substring(0, len);
  25. trunc = trunc.replace(/\w+$/, '');
  26.  
  27. /* Add an ellipses to the end and make it a link that expands
  28. the paragraph back to its original size */
  29. trunc += '<a href="#" ' +
  30. 'onclick="this.parentNode.innerHTML=' +
  31. 'unescape(\''+escape(p.innerHTML)+'\');return false;">' +
  32. '...<\/a>';
  33. p.innerHTML = trunc;
  34. }
  35. }
  36.  

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.