高级前端手写代码【Q649】如何去除字符串首尾空白字符

如何去除字符串首尾空白字符

更多描述 实现一个 trim 函数,如同原生的 Array.prototype.trim,以下有两个测试用例

//=> hello
"    hello   ".trim();
 
//=> hello
"    hello   \t\n".trim();

Issue 欢迎在 Gtihub Issue 中回答此问题: Issue 667

Author 回答者: shfshanyue

在正则表达式中,\s 指匹配一个空白字符,包括空格、制表符、换页符和换行符。等价于[ \f\n\r\t\v\u00a0\u1680\u180e\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff]

const trim = (str) => str.trim || str.replace(/^\s+|\s+$/g, "");

Author 回答者: heretic-G

function trim(str = "") {
  str = String(str);
  let left = 0;
  let right = str.length - 1;
  while (/\s/.test(str[left]) && left < right) {
    left += 1;
  }
 
  while (/\s/.test(str[right]) && left < right) {
    right -= 1;
  }
  return str.slice(left, right + 1);
}

Author 回答者: createhappymemoryforlife

const trim = (str) => str.trim || str.replace(/^\s+|\s+$/g, "");

const trim = str => str.trim?.() || str.replace(/^\s+|\s+$/g, ”)

Author 回答者: yxw007

function trim() {
  let str = this;
  let len = str.length;
  if (len <= 0) {
    return str;
  }
 
  let l = 0;
  let r = str.length - 1;
 
  while (l <= r) {
    if (str[l] == " ") {
      l++;
    }
    if (str[r] == " ") {
      r--;
    }
    if (str[l] != " " && str[r] != " ") {
      break;
    }
  }
 
  let res = str.slice(l, r + 1);
  return res;
}
 
String.prototype.trim = trim;
 
let s = "  123";
console.log(s.trim().length);
 
let s1 = "123 ";
console.log(s1.trim().length);
 
let s2 = " ";
console.log(s2.trim().length);
 
let s3 = "";
console.log(s3.trim().length);