Skip to content

Instantly share code, notes, and snippets.

@johanbrook
Created February 3, 2011 19:51
Show Gist options
  • Save johanbrook/810058 to your computer and use it in GitHub Desktop.
Save johanbrook/810058 to your computer and use it in GitHub Desktop.
A simple plugin for truncating long text strings.
(function($) {
/**
* A simple jQuery I wrote to truncate long links (in the post footers, amongst others).
*
* Usage:
* $("a.long-links").truncate( [ {limit: 40, truncationText: "..."} ] );
*
*/
$.fn.truncate = function(options) {
var settings = {
limit: 40,
truncationText: "..."
};
return this.each(function(){
var chars,
i,
$this = $(this),
str = $this.text();
if(options){
$.extend(settings, options);
}
chars = str.split('');
if (chars.length > settings.limit) {
for (i = chars.length - 1; i > -1; --i) {
if (i > settings.limit) {
chars.length = i;
}
else if (' ' === chars[i]) {
chars.length = i;
break;
}
}
chars.push(' '+settings.truncationText);
}
$this.text(chars.join(''));
});
};
}) (jQuery);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment