Skip to content

Instantly share code, notes, and snippets.

@nw
Created May 22, 2009 23:07
Show Gist options
  • Save nw/116412 to your computer and use it in GitHub Desktop.
Save nw/116412 to your computer and use it in GitHub Desktop.
Element.implement({
truncate : function(len,str,mid){
var str = str || '...';
var mid = !!mid;
var w = this.getSize().x;
if( w < len) return this;
var txt = this.get('text');
var char_size = Math.ceil(w / txt.length);
var keep = Math.ceil(len / char_size) - str.length;
if(mid) this.set('text', txt.slice(0,keep/2) + str + txt.slice(txt.length - keep/2) );
else this.set('text', txt.slice(0,keep) + str);
var w = this.getSize().x;
while(w > len || ((len-w) > char_size*2)){
char_size = Math.ceil(w / keep);
var take = Math.floor((len - w) / char_size);
keep += take;
if(mid) this.set('text', txt.slice(0,keep/2) + str + txt.slice(txt.length - keep/2) );
else this.set('text', txt.slice(0,keep) + str);
w = this.getSize().x;
}
return this;
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment