JavaScript String Trim Function

By Akbar

JavaScript doesn’t natively support the string trim (removing leading and trailing spaces) function, but this function is quite useful and required from time to time.

Fortunately, you can do this as easily as by just single line of code using regular expression and can add support to all the string objects using the JavaScript prototyping. Here is a quick sample of how you can do this:

String.prototype.trim = function()
{
	return this.replace(/^s+|s+$/g, '');
}

Once this is done. You can use the trim function on any string variable in the Javascript. Here is a quick demo:

var myname = "  Akbar  ";
 
alert(myname.trim());

Is’t this slick :-)

Tags: , , ,