Это даст вам немного больше контроля над положением многоточия и текстом заполнителя:
function ellipsis(str, maxLength, ellipsisLocationPercentage,placeholder) {
/*
ARGUMENTS:
str - the string you want to maninpulate
maxLength - max number of characters allowed in return string
ellipsisLocationPercentage (optional) - How far (percentage wise) into the return string you want the ellipses to be placed
Examples:
.85 : This is a very long string. This is a very long string. This is a very long string. This is a ver[...]very long string.
.25 : This is a very long string. [...]g. This is a very long string. This is a very long string. This is a very long string.
placeholder (optional) - this will be used to replace the removed substring. Suggestions : '...', '[..]', '[ ... ]', etc....
*/
if(ellipsisLocationPercentage == null || isNaN(ellipsisLocationPercentage) || ellipsisLocationPercentage >= 1 || ellipsisLocationPercentage <= 0){
//we've got null or bad data.. default to something fun, like 85% (that's fun, right??)
ellipsisLocationPercentage = .85;
}
if(placeholder == null || placeholder ==""){
placeholder = "[...]";
}
if (str.length > (maxLength-placeholder.length)) {
//get the end of the string
var beginning = str.substr(0, (maxLength - placeholder.length)*ellipsisLocationPercentage );
var end = str.substr(str.length-(maxLength - placeholder.length) * (1-ellipsisLocationPercentage));
return beginning + placeholder + end;
}
return str;
}
Вы можете вызвать эту функцию, вызвав:
ellipsis("This is a very long string. Be Scared!!!!", 8);//uses default values
ellipsis("This is a very long string. Be Scared!!!!", 8,.5);//puts ellipsis at half way point
ellipsis("This is a very long string. Be Scared!!!!", 8,.75,'<..>');//puts ellipsis at 75% of the way into the string and uses '<..>' as the placeholder