Use jQuery to Create Excerpts for Text Elements

Share this article

This is how you can use jQuery to limit characters inside a textarea. It is a function to set the maximum length of characters for any page element. You could use it to create excerpts for posts on your blog for example. See more jQuery .each Examples.

Demo

(function($) { 
	// jQuery function to set a maximum length or characters for a page element it can handle mutiple elements
        $.fn.createExcerpts = function(elems,length,more_txt) {
		$.each($(elems), function() { 
			var item_html = $(this).html(); //
			item_html = item_html.replace(/< /?[^>]+>/gi, ''); //replace html tags
			item_html = jQuery.trim(item_html);  //trim whitespace
			$(this).html(item_html.substring(0,length)+more_txt);  //update the html on page
		});
		return this; //allow jQuery chaining 
	}
})(jQuery);

And this is how you use it:

//example call
$().createExcerpts('.blogpost',280,'...');
Sam DeeringSam Deering
View Author

Sam Deering has 15+ years of programming and website development experience. He was a website consultant at Console, ABC News, Flight Centre, Sapient Nitro, and the QLD Government and runs a tech blog with over 1 million views per month. Currently, Sam is the Founder of Crypto News, Australia.

jQuery
Share this article
Read Next
Get the freshest news and resources for developers, designers and digital creators in your inbox each week
Loading form