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
Sam Deering is a Front-end Web Developer who specialises in JavaScript & jQuery. Sam is driven and passionate about sharing his knowledge to educate others.

Free Guide:

How to Choose the Right Charting Library for Your Application

How do you make sure that the charting library you choose has everything you need? Sign up to receive this detailed guide from FusionCharts, which explores all the factors you need to consider before making the decision.

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

Learn JavaScript for free!
Free course: Introduction to JavaScript

Yours when you take up a free 14-day SitePoint Premium trial.