How to trim a string in javascript?
+12
A:
There are a lot of implementations that can be used. The most obvious seems to be something like this:
String.prototype.trim = function() {
return this.replace(/^\s+|\s+$/g, "");
};
" foo bar ".trim(); // "foo bar"
Gumbo
2009-01-31 15:14:23
+5
A:
Simple version here What is a general function for JavaScript trim?
function trim(str) {
return str.replace(/^\s+|\s+$/g,"");
}
Mark Davidson
2009-01-31 15:15:16
+2
A:
The trim from jQuery is convenient if you are already using that framework.
I tend to use jQuery often, so trimming strings with it is natural for me. But it's possible that there is backlash against jQuery out there? :)
barneytron
2009-01-31 15:16:43
Use a framework to trim a string?
Christian Nunciato
2009-01-31 15:39:58
Thanks for the feedback, but that's not my point, so I'll need to rephrase my post. My thinking is really is that if jQuery has already been included, then when why not use it?
barneytron
2009-01-31 15:44:59
+5
A:
see this
String.prototype.trim=function(){a=this.replace(/^\s+/,'');return a.replace(/\s+$/,'');};
String.prototype.ltrim=function(){return this.replace(/^\s+/,'');}
String.prototype.rtrim=function(){return this.replace(/\s+$/,'');}
String.prototype.fulltrim=function(){return this.replace(/(?:(?:^|\n)\s+|\s+(?:$|\n))/g,'').replace(/\s+/g,' ');}
Pradeep Kumar Mishra
2009-01-31 15:26:30