[Javascript] trim function (regex)

liorean liorean at f2o.org
Thu May 6 05:11:29 CDT 2004


I'd prefer one that works on multiple lines. Something like this:

String.prototype.trim=function(){
     return this.replace(/^\s+|\s+$/gm,'');
}

However, that doesn't work in the ie5.0 JScript engine, and probably not 
in the nn4 JavaScript engine either, so the following gives better support:

String.prototype.trim=function(){
     var
         r=/^\s+|\s+$/,
         a=this.split(/\n/g),
         i=a.length;
     while(i-->0)
         a[i]=a[i].replace(r,'');
     return a.join('\n');
}

Or maybe this:


String.prototype.trim=function(){
     var
         s='',
         r=/^\s+|\s+$/,
         a=this.split(/\n/g),
         i=a.length;
     while(i-->0)
         s+=a[i].replace(r,'')+'\n';
     return s;
}

I haven't benchmarked them, but I belive the first one would be slightly 
more optimised.
-- 
David "liorean" Andersson

ViewStyles, ViewScripts, SwitchStyles and GraphicsInfo bookmarklets:
<http://liorean.web-graphics.com/>
Hangouts:
<http://codingforums.com/> <http://yourmusicforums.com/>



More information about the Javascript mailing list