Score code, devs, and debt fast.

Start free trial

Use jQuery to Create Excerpts for Text Elements

Sam Deering
Sam Deering
Published in
·Updated:

Share this article

SitePoint Premium
Stay Relevant and Grow Your Career in Tech
  • Premium Results
  • Publish articles on SitePoint
  • Daily curated jobs
  • Learning Paths
  • Discounts to dev tools

7 Day Free Trial. Cancel Anytime.

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 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

Subscribe to our newsletter

Get the freshest news and resources for developers, designers and digital creators in your inbox each week

© 2000 – 2025 SitePoint Pty. Ltd.
This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.