Many modern browsers (such as Firefox 3, Opera 11, Safari 5.x, Chrome 10, Internet Explorer 9 in standards mode) support the string.trim() method, which allows you to rewrite the above much shorter:
str = str.trim()
For browsers that do not support string.trim(), e.g. Internet Explorer 8 or earlier, you can add your own trim() method to string object's prototype by including the following script in the <HEAD> section of your page, prior to any script that uses string.trim():
if (!String.prototype.trim) {
String.prototype.trim = function() {
return this.replace(/^\s+|\s+$/g,'');
}
}
str = str.trim()
For browsers that do not support string.trim(), e.g. Internet Explorer 8 or earlier, you can add your own trim() method to string object's prototype by including the following script in the <HEAD> section of your page, prior to any script that uses string.trim():
if (!String.prototype.trim) {
String.prototype.trim = function() {
return this.replace(/^\s+|\s+$/g,'');
}
}