The question says it all; JS doesn\'t seem to have a native trim() method.
Why not just modify the String prototype? Why not steal the trim function from an open source library, like I did here with YUI? (Do you really need to load and entire framework for this simple taks?) Put them together and you get this:
String.prototype.trim = function() {
try {
return this.replace(/^\s+|\s+$/g, "");
} catch(e) {
return this;
}
}
var s = " hello ";
alert(s.trim() == "hello"); // displays true
I use this.
String.prototype.trim = function() {
return this.replace(/^\s+|\s+$/g,"");
}
A slightly tinier version of @Pat's.
return str.replace( /^\s+|\s+$/g, '' );
I know this question is ancient but now, Javascript actually does have a native .trim()
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/Trim
Actually, with jQuery this seems to be the way:
jQuery.trim(string)
(Reference)
Well, as a lot of people always says, the trim function works pretty well, but if you don't want to use a whole framework just to perform a trim, it may be useful to take a look at its implementation. So here it is:
function( text ) { return (text || "").replace( /^(\s|\u00A0)+|(\s|\u00A0)+$/g, "" );}
The main advantages I see in this implementation, comparing to other solution already proposed here are: