Below you will find pages that utilize the taxonomy term “String”
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: [sourcecode language=“javascript”]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; };[/sourcecode] To use it, just call the function from a string property in your favorite templating engine: Angular, jsRender, Knockout….: [sourcecode language=“javascript”]order.description.ellipsize();[/sourcecode] 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.