javascript: show only a part of a long string (ellipsis)
Anatoly Mironov
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….:
order.description.ellipsize();This function takes an argument maxLength (default 100 chars). It doesn’t cut your text in the middle of a word, that’s why it looks after a whitespace in range of maxLength-20 and maxLength.
comments from wordpress
Mayur — 2013-02-02
While working on my upcoming cool project, I wanted a JavaScript function that will perform an Ellipsis, bare in mind that I usually use C# and already have a .NET method that will do just that. However, in this case since my web application is 90% JS, I figured I could just do that client side. Here is what I came up with, I just wrote this 5 minutes ago, so use at your own risk.
Anatoly Mironov — 2013-02-02
Great. Did you want to share your solution? Did it disappear when you saved the comment?