String.prototype.trim = function() { return this.replace(/^\s+|\s+$/, ''); };
// Removes leading whitespaces function LTrim( value ) { var re = /\s*((\S+\s*)*)/; return value.replace(re, "$1"); } // Removes ending whitespaces function RTrim( value ) { var re = /((\s*\S+)*)\s*/; return value.replace(re, "$1"); } // Removes leading and ending whitespaces function trim( value ) { return LTrim(RTrim(value)); }
eg. try:
<body onload="test()">
<script>
String.prototype.trim = function() { return this.replace(/^\s+|\s+$/, ''); };
function test() {
var str = " a ";
alert("Original string: '" + str + "'");
str = str.trim();
alert("Incompletely stripped string: '" + str + "'");
}
</script>
ie. It doesn't strip all whitespace. This is because the regular expression should be: this.replace(/^\s+|\s+$/g, "");
eg. String.prototype.trim = function() { return this.replace(/^\s+|\s+$/g, ""); };