Use jQuery to Create Excerpts for Text Elements

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.

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,'...'); 

Free book: Jump Start HTML5 Basics

Grab a free copy of one our latest ebooks! Packed with hints and tips on HTML5's most powerful new features.

  • John Blackshaw

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

  • http://www.roniwahyu.com 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?

    tnx!

  • Hunor

    Thanks. It works for me…