Skip to content

Instantly share code, notes, and snippets.

@Edukanezza
Created April 29, 2015 20:54
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save Edukanezza/9aa816c7718e3f62271a to your computer and use it in GitHub Desktop.
Save Edukanezza/9aa816c7718e3f62271a to your computer and use it in GitHub Desktop.
Trim text down and add ...
// Trim text.
function trimText( jquery_obj_to_trim, trim_length ){
var currentText = jquery_obj_to_trim.text();
var newLength = trim_length;
var currentTextTrimmed = currentText.substr(0, newLength);
var endOfCurrentText = /\W?\s?\b\w+\W*?$/.exec( currentTextTrimmed );
if( endOfCurrentText === null ) return;
var endOfCurrentTextLength = endOfCurrentText[0].length;
currentTextTrimmed = currentText.substr(0, newLength - endOfCurrentTextLength );
var newText = currentTextTrimmed + "...";
jquery_obj_to_trim.text( newText );
}
//Example usage
trimText( $(".hero-news p") , 180 );
@namklabs
Copy link

😄

@namklabs
Copy link

I've made some significant improvements. https://gist.github.com/namklabs/e1550d7f795e1daf2241

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment