Does anyone have a more sophisticated solution/library for shortening strings with JavaScript, than the obvious one:
if(string.length > 25) {
string = string.substring(0,24)+"...";
}
Does anyone have a more sophisticated solution/library for shortening strings with JavaScript, than the obvious one:
if(string.length > 25) {
string = string.substring(0,24)+"...";
}
String.prototype.trunc = function(n){
return this.substr(0,n-1)+(this.length>n?'...':'');
};
Now you can do:
var s = 'not very long';
s.trunc(25); //=> not very long
s.trunc(5); //=> not ...
if you mean truncating at the last word boundary of a string with 'more sophisticated' then this may be what you want:
String.prototype.trunc =
function(n,useWordBoundary){
var toLong = this.length>n,
s_ = toLong ? this.substr(0,n-1) : this;
s_ = useWordBoundary && toLong ? s_.substr(0,s_.lastIndexOf(' ')) : s_;
return toLong ? s_ +'...' : s_;
};
now you can do:
s.trunc(11,true) //=>not very...
Most modern Javascript frameworks (JQuery, Prototype, etc...) have a utility function tacked on to String that handles this.
Here's an example in Prototype:
'Some random text'.truncate(10);
// -> 'Some ra...'
This seems like one of those functions you want someone else to deal with/maintain. I'd let the framework handle it, rather than writing more code.
Here's my solution, which has a few improvements over other suggestions:
String.prototype.truncate = function(){
var re = this.match(/^.{0,25}[\S]*/);
var l = re[0].length;
var re = re[0].replace(/\s$/,'');
if(l < this.length)
re = re + "…";
return re;
}
// "This is a short string".truncate();
"This is a short string"
// "Thisstringismuchlongerthan25characters".truncate();
"Thisstringismuchlongerthan25characters"
// "This string is much longer than 25 characters and has spaces".truncate();
"This string is much longer…"
It:
Note that this only needs to be done for Firefox. All other browsers support a CSS solution:
p {
white-space: nowrap;
width: 100%; /* IE6 needs any width */
overflow: hidden; /* "overflow" value must be different from "visible"*/
-o-text-overflow: ellipsis; /* Opera */
text-overflow: ellipsis; /* IE, Safari (WebKit) */
}
The irony is I got that code snippet from Mozilla MDC.
Just another method you can use for truncating large text strings
function truncate( text, length, ellipsis )
{
// length ( default = 20 )
if (typeof length == 'undefined') var length = 20;
// ellipsis display ( default = "..." )
if (typeof ellipsis == 'undefined') var ellipsis = '...';
// if text length does not exceed limit then return text as is
if (text.length < length) return text;
// convert text string
for (var i = length-1; text.charAt(i) != ' '; i--) {
length--;
}
return text.substr(0, length) + ellipsis;
}