Extend String with trim functions
This is a neat Javascript extension to the String object contributed by Nils Forsman.
Here's the code that adds trim, ltrim and rtrim to the String object:
String.prototype.trim = function() {
return this.replace(/(^\s*)|(\s*$)/g, '');
};
String.prototype.ltrim = function() {
return this.replace(/^\s*/g, '');
};
String.prototype.rtrim = function() {
return this.replace(/\s*$/g, '');
};
And a little code snippet to test the above functions:
var testString = " test ";
testString = testString .trim();
alert("#" + testString + "#");
Related posts: