开发者

Can this limitChars function be improved?

开发者 https://www.devze.com 2023-01-21 19:04 出处:网络
I\'ve just written a limitChars() function. var limitChars = function(str, limit, endChar, preserveWord) {

I've just written a limitChars() function.

var limitChars = function(str, limit, endChar, preserveWord) {
  str = $.trim(str);
  var strLength = str.length;
  if (strLength 开发者_Python百科<= 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).


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!


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;

}


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消