3.驼峰化字符串

书诚小驿2024/10/01前端面经算法JavaScript

驼峰化字符串

题目

驼峰化字符串,考虑_、-、at 符号等多种分隔符,可能有 a--b 这种连续分隔符、a_b_c 组合分隔符,实现的函数只接受一个参数

示例

console.log(camelCase("hello_world")); // 输出: helloWorld
console.log(camelCase("a--b")); // 输出: aB
console.log(camelCase("this-is-an_example")); // 输出: thisIsAnExample
console.log(camelCase("multiple at separators")); // 输出: multipleAtSeparators
console.log(camelCase("a-b_c--d_at-e-f")); // 输出: aBCDEf

提示

DETAILS
  1. 分隔符定义:使用正则表达式 /_|-|(?:at)/ 来匹配下划线、连字符以及 "at" 字符串

  2. 分割字符串:使用 split 方法将字符串分割为数组。

  3. 过滤空字符串:用 filter(Boolean) 去除任何空字符串,这可以处理连续分隔符的情况。

  4. 映射处理单词:通过 map 方法遍历数组,分别处理第一个单词和后续单词的大小写:

  • 第一个单词保持小写。
  • 后续单词的首字母转为大写,其余字母转为小写。
  1. 连接单词:最后使用 join('') 将处理后的单词连接成一个字符串。

参考答案

DETAILS
<script>
    function camelCase(str) {
      // 定义分隔符,包括下划线、连字符、空格和 "at"
      const delimiters = /[_\- ]+|(?=\bat\b)/;

      return str
        .split(delimiters) // 根据分隔符分割
        .filter(Boolean) // 过滤掉空字符串
        .map((word, index) => {
          if (index === 0) {
            // 第一个单词保持小写
            return word.toLowerCase();
          }
          // 其他单词首字母大写,其余小写
          return word.charAt(0).toUpperCase() + word.slice(1).toLowerCase();
        })
        .join(''); // 连接为驼峰化字符串
    }

    // 示例使用
    console.log(camelCase("multiple at separators")); // 输出: multipleAtSeparators
    console.log(camelCase("hello_world")); // 输出: helloWorld
    console.log(camelCase("a--b")); // 输出: aB
    console.log(camelCase("this-is-an_example")); // 输出: thisIsAnExample
    console.log(camelCase("a-b_c--d_at-e-f")); // 输出: aBCDEf
</script>
最后更新时间' 2025/1/3 14:16:58