字符串去除前后空格

手写 trim 方法清除字符串前后空格

问题

写一个 function,清除字符串前后的空格。

解答

方法一:使用原生 trim()

const str = '  hello world  ';
console.log(str.trim()); // 'hello world'

方法二:正则表达式实现

function trim(str) {
  // ^ 匹配开头,$ 匹配结尾
  // \s 匹配空白字符(空格、制表符、换行符等)
  // + 匹配一个或多个
  return str.replace(/^\s+|\s+$/g, '');
}

// 测试
console.log(trim('  hello world  ')); // 'hello world'
console.log(trim('\t\nhello\n\t'));   // 'hello'

方法三:循环遍历实现

function trim(str) {
  if (typeof str !== 'string') return str;
  
  let start = 0;
  let end = str.length - 1;
  
  // 从头部找到第一个非空白字符
  while (start <= end && isWhitespace(str[start])) {
    start++;
  }
  
  // 从尾部找到第一个非空白字符
  while (end >= start && isWhitespace(str[end])) {
    end--;
  }
  
  return str.slice(start, end + 1);
}

function isWhitespace(char) {
  return char === ' ' || char === '\t' || char === '\n' || char === '\r';
}

// 测试
console.log(trim('  hello world  ')); // 'hello world'
console.log(trim('   '));              // ''
console.log(trim('hello'));            // 'hello'

方法四:分别实现 trimStart 和 trimEnd

function trimStart(str) {
  return str.replace(/^\s+/, '');
}

function trimEnd(str) {
  return str.replace(/\s+$/, '');
}

function trim(str) {
  return trimEnd(trimStart(str));
}

// 测试
console.log(trimStart('  hello  ')); // 'hello  '
console.log(trimEnd('  hello  '));   // '  hello'
console.log(trim('  hello  '));      // 'hello'

关键点

  • \s 匹配所有空白字符:空格、制表符 \t、换行符 \n、回车符 \r
  • 正则 ^\s+ 匹配开头空白,\s+$ 匹配结尾空白
  • ES5 原生支持 trim(),ES2019 新增 trimStart()trimEnd()
  • 循环实现的时间复杂度为 O(n),空间复杂度为 O(1)