我如何从字符串的开始和结束删除所有空白?


当前回答

自IE9+以来的所有浏览器都有trim()方法用于字符串:

" \n test \n ".trim(); // returns "test" here

对于那些不支持trim()的浏览器,你可以使用MDN的这个填充:

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

也就是说,如果使用jQuery, $.trim(str)也是可用的,并处理undefined/null。


看到这个:

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

其他回答

虽然上面有一堆正确答案,但应该注意的是,JavaScript中的String对象在ECMAScript 5中有一个原生的.trim()方法。因此,在理想情况下,任何尝试创建trim方法原型的尝试都应该首先检查它是否已经存在。

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

本机添加于: JavaScript 1.8.1 / ECMAScript

因此支持:

Firefox: 3.5 +

Safari: 5 +

ie浏览器:IE9+(仅限标准模式下)http://blogs.msdn.com/b/ie/archive/2010/06/25/enhanced-scripting-in-ie9-ecmascript-5-support-and-more.aspx

铬: 5+

工作:10 + 5。

ECMAScript 5支持表:http://kangax.github.com/es5-compat-table/

从angular js项目中修剪代码

var trim = (function() {

  // if a reference is a `String`.
  function isString(value){
       return typeof value == 'string';
  } 

  // native trim is way faster: http://jsperf.com/angular-trim-test
  // but IE doesn't have it... :-(
  // TODO: we should move this into IE/ES5 polyfill

  if (!String.prototype.trim) {
    return function(value) {
      return isString(value) ? 
         value.replace(/^\s*/, '').replace(/\s*$/, '') : value;
    };
  }

  return function(value) {
    return isString(value) ? value.trim() : value;
  };

})();

并将其命名为trim(" hello ")

我有一个库,使用修剪。所以通过使用下面的代码来解决它。

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

String.prototype.trimLeft = String.prototype.trimLeft || function () {
    return this.replace(/^\s+/, "");
};

String.prototype.trimRight = String.prototype.trimRight || function () {
    return this.replace(/\s+$/, "");
};

String.prototype.trimFull = String.prototype.trimFull || function () {
    return this.replace(/(?:(?:^|\n)\s+|\s+(?:$|\n))/g, "").replace(/\s+/g, " ");
};

无耻地从马特·杜雷格那里偷来的。

我知道这个问题三年前就有人问过了。现在,String.trim()是在JavaScript中原生添加的。举个例子,你可以像下面这样直接修剪,

document.getElementById("id").value.trim();