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


当前回答

使用简单的代码

var str = "       Hello World!        ";
alert(str.trim());

浏览器支持

Feature         Chrome  Firefox Internet Explorer   Opera   Safari  Edge
Basic support   (Yes)   3.5     9                   10.5    5       ?

为旧浏览器添加原型

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

其他回答

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

不知道有什么虫子可以藏在这里,但我用这个:

var some_string_with_extra_spaces="   goes here    "
console.log(some_string_with_extra_spaces.match(/\S.*\S|\S/)[0])

或者这个,如果文本包含回车:

console.log(some_string_with_extra_spaces.match(/\S[\s\S]*\S|\S/)[0])

另一个尝试:

console.log(some_string_with_extra_spaces.match(/^\s*(.*?)\s*$/)[1])

从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 ")

适用于IE9+及其他浏览器

function trim(text) {
    return (text == null) ? '' : ''.trim.call(text);
}

如果使用jQuery,请使用jQuery.trim()函数。例如:

if( jQuery.trim(StringVariable) == '')