Trim string in JavaScript?

如何修剪JavaScript中的字符串?


All browsers since IE9+ have trim() .

For those browsers who does not support trim() , you can use this polyfill from MDN:

if (!String.prototype.trim) {
    (function() {
        // Make sure we trim BOM and NBSP
        var rtrim = /^[suFEFFxA0]+|[suFEFFxA0]+$/g;
        String.prototype.trim = function() {
            return this.replace(rtrim, '');
        };
    })();
}

See this:

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

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,' ');};

The trim from jQuery is convenient if you are already using that framework.

$.trim('  your string   ');

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? :)


Although there are a bunch of correct answers above, it should be noted that the String object in JavaScript has a native .trim() method as of ECMAScript 5. Thus ideally any attempt to prototype the trim method should really check to see if it already exists first.

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

Added natively in: JavaScript 1.8.1 / ECMAScript 5

Thus supported in:

Firefox: 3.5+

Safari: 5+

Internet Explorer: IE9+ (in Standards mode only!) http://blogs.msdn.com/b/ie/archive/2010/06/25/enhanced-scripting-in-ie9-ecmascript-5-support-and-more.aspx

Chrome: 5+

Opera: 10.5+

ECMAScript 5 Support Table: http://kangax.github.com/es5-compat-table/

链接地址: http://www.djcxy.com/p/26770.html

上一篇: 变量名称在函数签名中的含义是什么?

下一篇: 在JavaScript中修剪字符串?