A 'truncate words' would take a string of words and return only the first, let's say, 10 words.
In dojo (javascript library) they have such a function, whose code is this:
truncatewords: function(value, arg){
// summary: Truncates a string after a certain number of words
// arg: Integer
// Number of words to truncate after
arg = parseInt(arg);
if(!arg){
return value;
}
for(var i = 0, j = value.length, count = 0, current, last; i < value.length; i++){
current = value.charAt(i);
if(dojox.dtl.filter.strings._truncatewords.test(last)){
if(!dojox.dtl.filter.strings._truncatewords.test(current)){
++count;
if(count == arg){
return value.substring(0, j + 1);
}
}
}else if(!dojox.dtl.filter.strings._truncatewords.test(current)){
j = i;
}
last = current;
}
return value;
}
where dojox.dtl.filter.strings._truncatewords.
is /(&.*?;|<.*?>|(\w[\w-]*))/g
Why isn't this written like so:
function truncate(value,arg) {
var value_arr = value.split(' ');
if(arg < value_arr.length) {
value = value_arr.slice(0,arg).join(' '); }
return value;
}
and what are the differences?