I am currently using the code below to truncate text:
function truncate($elem, wordNum){
var words = $elem.find('p').text().trim().split(/\s+/).slice(0,wordNum);
var replacement = $("<p/>").text(words.join(" ") + "...");
$elem.find('.read-more').click(function(){
if($(this).text() == 'Read More'){
replacement.hide();
$elem.find('p:eq(1)').show();
} else if($(this).text() == 'Read Less'){
replacement.show();
$elem.find('p:eq(1)').hide();
}
$(this).text(function(i,old){
return old=='Read More' ? 'Read Less' : 'Read More';
});
return false
});
$elem.find('p:first').before(replacement);
$elem.find('p:eq(1)').hide();
}
truncate($("p"), 5);
Works, but it's not the most efficient solution. Is there a better way ?
\s+
to match multiple spaces. \$\endgroup\$