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


当前回答

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

其他回答

你可以使用纯JavaScript来实现:

function trimString(str, maxLen) {
if (str.length <= maxLen) {
return str;
}
var trimmed = str.substr(0, maxLen);
return trimmed.substr(0, trimmed.lastIndexOf(' ')) + '…';
}

// Let's test it

sentenceOne = "too short";
sentencetwo = "more than the max length";

console.log(trimString(sentenceOne, 15));
console.log(trimString(sentencetwo, 15));

Flagrant Badassery有11个不同的修剪基准信息:

http://blog.stevenlevithan.com/archives/faster-trim-javascript

毫无疑问,基于regexp的循环比传统循环慢。


这是我个人的。这段代码太旧了!我为JavaScript1.1和Netscape 3编写了它,从那以后它只进行了轻微的更新。(最初使用String.charAt)

/**
 *  Trim string. Actually trims all control characters.
 *  Ignores fancy Unicode spaces. Forces to string.
 */
function trim(str) {
    str = str.toString();
    var begin = 0;
    var end = str.length - 1;
    while (begin <= end && str.charCodeAt(begin) < 33) { ++begin; }
    while (end > begin && str.charCodeAt(end) < 33) { --end; }
    return str.substr(begin, end - begin + 1);
}

虽然上面有一堆正确答案,但应该注意的是,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/

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

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

下面是它的TypeScript格式:

var trim: (input: string) => string = String.prototype.trim
    ? ((input: string) : string => {
        return (input || "").trim();
    })
    : ((input: string) : string => {
        return (input || "").replace(/^\s+|\s+$/g,"");
    })

如果本机原型不可用,它将回退到正则表达式。