views:

64

answers:

3

I've just written a limitChars() function.

var limitChars = function(str, limit, endChar, preserveWord) {
  str = $.trim(str);
  var strLength = str.length;
  if (strLength <= limit) {
    return str;
  }

  if (limit == 0) {
    return '';
  }

  endChar = endChar || '…';

  if (preserveWord && ! str.substr(limit, 1).match(/\s/)) {
    while ( limit < strLength && ! str.substr(limit, 1).match(/\s/)) {
      limit++;
    }
  }

   return $.trim(str.substr(0, limit)) + endChar;     
}

For learning purposes, I like to post my solution here and see if anyone can improve it (and I often find I've overlooked something, and we all learn :) )

So, tell me where I can improve this piece of code, please :)

(oh I use jQuery's $.trim(), but if you want to use any more jQuery specific functions, feel free to).

A: 

We can simply do the below right

 function ShortentText(text, limit) {

var temp;
if (text.length - 1 > limit) {
    temp = text.substring(0, limit-3) + '...';
}
else {
    temp = text;
}
return temp;

}

gov
I mean to say without cutting out any of the features of mine :) Mine also assumed that the end char would be additional after the cut off. Also, may as well use the Unicode ellipsis.
alex
A: 

I don't know if it's a better solution, but this would also work:

var limitChars = function(str, limit, endChar, preserveWord) {
  if($.trim(str).length<limit)
 return $.trim(str);
  else if(!preserveWord)
 return $.trim(str).substr(0,limit).concat(endChar||'…');
  else {
    var strArr = $.trim(str).split(" ");
    var i=-1;
    var retStr = "";
    while(i+1<strArr.length &&  retStr.concat(" ", strArr[i+1]).length < limit)
  retStr = retStr.concat(" ", strArr[++i]);
    return retStr.concat(endChar|| '…');
  }
}

Also, I would add default parameters.

Aspelund
Thanks for your answer. JavaScript [doesn't allow](http://jsbin.com/ujaro) default params like that, however. I do provide default params - the ellipsis for `endChar` and a *falsy* value (`undefined`) for `preserveWord`. I also tried to avoid recalculating the `length` for every iteration.
alex
Oh, thanks, I didn't realize that.
Aspelund
+1  A: 

Since indexOf takes an optional second argument fromIndex, we can implement the function as such:

function limitChars(str, limit, endChar, preserveWord) {
    str = $.trim(str);
    return (str.length > limit) ? str.substring(0, (preserveWord ? str.indexOf(' ', limit) : limit)) + (endChar || '…') : str;
}

A lot less readable, but I think you get the idea. :)

Edit: I just realised that I've missed a part of the original script that will append endChar only if the length of the string is longer than limit. Time for another ternary operator!

Yi Jiang