Posts
read more
javascript: show only a part of a long string (ellipsis)
Ellipsis (…) is a character which indicates that the content is to wide. There are many solutions to truncate the text and show an ellipsis: in javascript and css. I want to share my humble function which extends the String.prototype:
String.prototype.ellipsize = function (maxLength) {
maxLength = maxLength || 100;
if (this.length <= maxLength) {
return this;
}
var text = this.toString()
.replace(/[\r\n]/g,
""), max = maxLength, min = maxLength - 20,
elipsized, tryExtract = function () {
var regex = new RegExp("^.{" + min + "," + max + "}\\s"),
match = text.match(regex);
if (match) {
elipsized = match[0].replace(/\.?\s$/, '…');
}
else {
//well, there were no \s between min and max
min = min - 20;
tryExtract();
}
};
if (min <= 0) {
return text;
}
tryExtract();
return elipsized || text;
};To use it, just call the function from a string property in your favorite templating engine: Angular, jsRender, Knockout….: