Use jQuery to Create Excerpts for Text Elements

By Sam Deering

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.


(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 

And this is how you use it:

//example call

Free Guide:

7 Habits of Successful CTOs

"What makes a great CTO?" Engineering skills? Business savvy? An innate tendency to channel a mythical creature (ahem, unicorn)? All of the above? Discover the top traits of the most successful CTOs in this free guide.

  • John Blackshaw

    Wow, this exactly what I’ve looking for! Thank you very much for this =)

  • roniwahyu

    Great! thanks… it’s helpfully

  • rich

    is there way this can work on an element which contains html elements such as images etc and text. I want to use the code to limit characters on blog posts output by a cms but there maybe images in the div I dont want removed which this code dosent account for or work as is?

  • meiti

    tnx. BUT …

    yes it works fine on texts with length more than given arg properly, but works on texts with length less than given arg too ! and that’s wrong.
    would you plz fix it as I’m not familiar with js?


  • Hunor

    Thanks. It works for me…

  • Jan R. Biasi

    Throws a syntax error in my case “unexpected character ^” in your regex…

  • Jan R. Biasi

    Your solution with selecting an element isn’t pretty good, try it like this:

Because We Like You
Free Ebooks!

Grab SitePoint's top 10 web dev and design ebooks, completely free!

Get the latest in JavaScript, once a week, for free.