1

Possible Duplicate:
How Can I Truncate A String In jQuery?

I'm pulling a feed from Facebook using jQuery and want to put a limit on the number of words/chars displayed in each message string.

i.e. If string contains more than 100 chars, it should stop at the nearest space and put '... read more '

How can I do this, simply?

Community
  • 1
  • 1
Quadrant6
  • 1,175
  • 2
  • 15
  • 25

2 Answers2

5
function truncateString (string, limit, breakChar, rightPad) {
    if (string.length <= limit) return string;

    var substr = string.substr(0, limit);
    if ((breakPoint = substr.lastIndexOf(breakChar)) >= 0) {
        if (breakPoint < string.length -1) {
            return string.substr(0, breakPoint) + rightPad;
        }
    }

    return string;

}

You can test this function here jsfiddle

Or use this code to test it

var text = 'The World Wide Web. When your average person on the street'; console.log(truncateString(text, 52, ' ', '...'));

AlexandruSerban
  • 312
  • 2
  • 9
  • 1
    Maybe you could rather put the `return string;` at the end, because it returns `undefined` in certain cases now. – pimvdb Nov 25 '12 at 11:22
  • You should add return string for strings that do not have the delimiter in them or you can return the truncated substring `return substr + rightPad`; – AlexandruSerban Nov 25 '12 at 12:30
2

You can write a simple function to do that, pure and straight javascript, like:

// Function that truncates string at the 10th char and appends '... (read more)'
// if the string has more than 10 chars
var ellipsize_special = function (string) {
  if (string.length > 10) { 
      return string.substring(0,10) + "... (read more)";
  } else {
      return string;
  }
}

Testing it:

 var short_str = "apple";
 var long_str = "pineapple juice";
 ellipsize_special(short_str);
 ellipsize_special(long_str);

Caveat: it is a simple method. Ellipsizing correctly would involve truncating the string at the first blank character before the char limit. Browsers have support to that (by means of CSS parameters), but they do not add the "read more" string that you wanted, and it is a mess trying to make that work properly, at least the last time I tried, in Opera, Firefox, Chrome, IE...

Castilho
  • 3,147
  • 16
  • 15