-
-
Save namklabs/e1550d7f795e1daf2241 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Trim text. | |
/* | |
- Respects word boundaries by default (will not chop a word up to create ellipses by default). | |
- Allows for ellipses or no ellipses. | |
*/ | |
function trimText( jquery_obj_to_trim, int_trim_length, bool_ellipses, bool_respect_word_boundaries ){ | |
var ellipses; | |
if( typeof bool_ellipses === "undefined" ){ | |
ellipses = true; // ellipses enabled by default. | |
} else { | |
ellipses = bool_ellipses; | |
} | |
var wordBoundaries; | |
if( typeof bool_respect_word_boundaries === "undefined" ){ | |
wordBoundaries = true; | |
} else { | |
wordBoundaries = bool_respect_word_boundaries; | |
} | |
var currentText = jquery_obj_to_trim.eq(0).html(); | |
var newLength = int_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 - ( wordBoundaries ? endOfCurrentTextLength : 0 ) ); | |
var newText = currentTextTrimmed + ( bool_ellipses ? "..." : "" ); | |
jquery_obj_to_trim.eq(0).html( newText ); | |
} | |
//Example usage | |
trimText( $(".hero-news p:first") , 180 ); // Do not pass in multiple elements via your jQuery object. | |
$(".hero-news p").not(":first").remove(); // Remove subsequent p's after the trimmed first one. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment