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).