FE-Interview icon indicating copy to clipboard operation
FE-Interview copied to clipboard

给 JavaScript 的 String 原生对象添加一个名为 trim 的原型方法,用于截取字符串前后的空白字符

Open lgwebdream opened this issue 5 years ago • 4 comments

lgwebdream avatar Jul 06 '20 17:07 lgwebdream

扫描下方二维码,获取答案以及详细解析,同时可解锁800+道前端面试题。

lgwebdream avatar Jul 06 '20 17:07 lgwebdream

~(function(){
  String.prototype.myTrim = function(){
    return this.replace(/^\s*|\s*$/g, '');
  }
})();
console.log('   hello world '.myTrim()); // hello world
console.log('abcd '.myTrim()); // abcd

GolderBrother avatar Sep 02 '20 06:09 GolderBrother


String.prototype.trim = function () {
  if (this.length <= 0) {
    return "";
  }

  const that = this;
  let left = 0;
  let right = that.length - 1;

  while (left < that.length) {
    if (that[left] !== " ") {
      break;
    }

    left++;
  }

  while (right > left) {
    if (that[right] !== " ") {
      break;
    }

    right--;
  }

  console.log(`DEBUG: after trim left: ${left} right: ${right}`);
  return that.slice(left, right + 1);
};

"   hello world ".trim();

gaohan1994 avatar May 05 '24 11:05 gaohan1994

String.prototype.mytrim = function () {
                return this.replace(/^\s*|\s*$/g, '')
            }

        let s = '             aaa '
       console.log(s.mytrim())

Alicca-miao avatar Oct 01 '24 04:10 Alicca-miao