JavaScript trim 实现(去除字符串首尾指定字符)

1.正则实现

let str = `   hello world  !  `;
let _trim = function () {
  if (typeof this == "number") new Error("Invalid or unexpected token");
  if (typeof this !== "string")
    new Error("Cannot read property 'trim' of" + this);
  let reg = /^\s*|\s*$/g;
  return this.replace(reg, "");
};

String.prototype._trim = _trim;

2.substring 实现

//2、使用字符串方法实现:查找出第一个不是空格的字符和最后一个不是空格的字符,截取中间的内容即可
String.prototype._trim1 = function () {
  let startIndex = Math.max(this.search(/\S/), 0);
  let endIndex = this.search(/\S\s*$/) + 1;
  return this.substring(startIndex, endIndex);
};

3.for循环实现

String.prototype._trim2 = function () {
  var str = this,
    whitespace =
      " \n\r\t\f\x0b\xa0\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u200b\u2028\u2029\u3000";
  for (var i = 0, len = str.length; i < len; i++) {
    if (whitespace.indexOf(str.charAt(i)) === -1) {
      str = str.substring(i);
      break;
    }
  }
  for (i = str.length - 1; i >= 0; i--) {
    if (whitespace.indexOf(str.charAt(i)) === -1) {
      str = str.substring(0, i + 1);
      break;
    }
  }
  return whitespace.indexOf(str.charAt(0)) === -1 ? str : "";
};

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值