How to ellipse a string in JavaScript

Posted: November 26, 2010 in Quick Tips
Tags: , ,

This is a handy little string function I use all the time to ellipse strings in a page. Bascially you give it the total length you want and it truncates and adds the ellipses to the end of it. It extends the string class so it is available as a method off the string object.

Usage:

var str = 'This is a really long string';
str = str.ellipse(10);
//str is: 'This is...' total of 10 chars

 

string.prototype.ellipse = function (stringLength) {
  if (this.length > stringLength - 3)
    return this.substring(0, stringLength - 3) + '...';
  else
    return this;
};
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s