millermedeiros/amd-utils — Issue #4: Truncation returning incorrect results
Author: joshua-perez
Created: 2011-10-31 01:17:27+00:00
State: open

When testing your methods standalone, the returned truncated string is incorrect.

function truncate(str, maxChars, append){
maxChars = maxChars || 125;
append = append || '...';

str = trim(str);
if(str.length <= maxChars){
return str;
}
str = str.substr(0, maxChars - append.length + 1);
str = str.substr(0, str.lastIndexOf(' ')); //crop at last space
return str + append;
}

function trim(str){
return (str || '').replace(/^\s+|\s+$/g, '');
}

console.log(truncate('Lorem ipsum dolor sit amet', 6)); // ...
console.log(truncate('Lorem ipsum dolor sit amet', 7)); // …
console.log(truncate('Lorem ipsum dolor sit amet', 13)); // Lorem…