1. MDN 兼容旧版本写法

      1. String.prototype.trim = function () {
      2. return this.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '');
      3. };
    2. 常见解法

      1. String.prototype.trim = function() {
      2. return this.replace(/^\s+|\s+$/g, '');
      3. }
    3. 性能较好的解法

      1. String.prototype.trim = function() {
      2. var str = this,
      3. str = str.replace(/^\s+/, '');
      4. for (var i = str.length - 1; i >= 0; i--) {
      5. if (/\s/.test(str.charAt(i))) {
      6. str = str.substring(0, i + 1);
      7. break;
      8. }
      9. }
      10. return str;
      11. }