tags:

views:

2121

answers:

5

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
+1  A: 

Check this out.

Boris Pavlović
+5  A: 

Simple version here What is a general function for JavaScript trim?

function trim(str) {
        return str.replace(/^\s+|\s+$/g,"");
}
Mark Davidson
+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
Use a framework to trim a string?
Christian Nunciato
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
+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