Although there are a bunch of correct answers above, it should be noted that the String
object in JavaScript has a native .trim()
method as of ECMAScript 5. Thus ideally any attempt to prototype the trim method should really check to see if it already exists first.
if(!String.prototype.trim){
String.prototype.trim = function(){
return this.replace(/^\s+|\s+$/g,'');
};
}
Added natively in: JavaScript 1.8.1 / ECMAScript 5
Thus supported in:
Firefox: 3.5+
Safari: 5+
Internet Explorer: IE9+ (in Standards mode only!) http://blogs.msdn.com/b/ie/archive/2010/06/25/enhanced-scripting-in-ie9-ecmascript-5-support-and-more.aspx
Chrome: 5+
Opera: 10.5+
ECMAScript 5 Support Table: http://kangax.github.com/es5-compat-table/