Skip to content

实现一个方法,清除字符串前后的空格。

在JavaScript中,我们可以通过多种方式实现清除字符串前后空格的功能。

以下是几种常见的实现方法:

1. 使用原生String.trim()方法(最简单)

javascript
function trim(str) {
  return str.trim();
}

// 示例
console.log(trim('  hello world  ')); // 输出: "hello world"

2. 使用正则表达式实现

javascript
function trim(str) {
  return str.replace(/^\s+|\s+$/g, '');
}

// 示例
console.log(trim('  hello world  ')); // 输出: "hello world"

3. 手动实现(不使用trim或正则)

javascript
function trim(str) {
  let start = 0;
  let end = str.length - 1;
  
  // 找到前面第一个非空格字符的位置
  while (start <= end && str[start] === ' ') {
    start++;
  }
  
  // 找到后面第一个非空格字符的位置
  while (end >= start && str[end] === ' ') {
    end--;
  }
  
  // 返回去除空格后的子字符串
  return str.substring(start, end + 1);
}

// 示例
console.log(trim('  hello world  ')); // 输出: "hello world"

4. 兼容旧浏览器的实现(ES5之前)

javascript
function trim(str) {
  if (String.prototype.trim) {
    return str.trim();
  }
  return str.replace(/^\s+|\s+$/g, '');
}