工具函数 · 14/107
1. 抽象工厂模式 2. Adapter Pattern 3. Adapter Pattern 4. 实现一个支持柯里化的 add 函数 5. 计算两个数组的交集 6. 数组中的数据根据key去重 7. 实现一个add方法完成两个大数相加 8. 大数相加 9. bind、call、apply 的区别与实现 10. Bridge Pattern 11. Builder Pattern 12. 实现一个管理本地缓存过期的函数 13. 缓存代理 14. 转化为驼峰命名 15. 实现 (5).add(3).minus(2) 功能 16. 咖啡机进阶优化 17. 咖啡机状态管理 18. 常用设计模式总结 19. 咖啡机状态切换机制 20. 查找数组公共前缀(美团) 21. 实现一个compose函数 22. 并发请求调度器 23. 组合模式 24. 实现 console.log 代理方法 25. Decorator Pattern 26. 实现防抖和节流 27. 实现一个JS函数柯里化 28. 实现防抖函数(debounce) 29. Decorator Pattern 30. 手写深度比较isEqual 31. 消除 if-else 条件判断 32. 修改嵌套层级很深对象的 key 33. 设计模式应用 34. 验证是否是邮箱 35. 实现发布订阅模式 36. 外观模式 37. Facade Pattern 38. Factory Pattern 39. 工厂模式 40. 工厂模式实现 41. Flyweight Pattern 42. 前端常用设计模式与场景 43. 提取对象中所有value大于2的键值对 44. 用正则实现根据name获取cookie中的值 45. 获取今天的日期 46. ES6 之前的迭代器模式 47. 实现 getValue/setValue 函数来获取path对应的值 48. 验证是否是身份证 49. 迭代器模式 50. jQuery slideUp 动画队列堆积问题 51. 实现一个JSON.parse 52. 实现 LazyMan 任务队列 53. 实现一个JSON.stringify 54. 实现lodash的chunk方法--数组按指定长度拆分 55. 字符串最长的不重复子串 56. LRU 缓存算法 57. 查找字符串中出现最多的字符和个数 58. new 操作符的实现原理 59. 中介者模式 60. 中介者模式 61. 对象数组如何去重 62. 千分位格式化 63. 实现观察者模式 64. 观察者模式实例 65. 观察者模式 66. 实现观察者模式 67. 实现 padStart() 和 padEnd() 的 Polyfill 68. 判断是否是电话号码 69. Proxy Pattern 70. 代理模式:婚介所 71. Proxy Pattern 72. 代理模式 73. 实现上拉加载和下拉刷新 74. 生成随机数组并排序 75. 大文件断点续传实现 76. 使用 setInterval 模拟实现 setTimeout 77. 重构询价逻辑 78. 实现一个简单的路由 79. setTimeout 模拟实现 setInterval 80. RGB 转 Hex 颜色转换 81. setTimeout与setInterval实现 82. Simple Factory Pattern 83. 实现单例模式 84. 实现一个 sleep 函数 85. 状态模式 86. State Pattern 87. 策略模式 88. Strategy Pattern 89. Storage 单例封装 90. 策略模式 91. 计算字符串字节长度 92. 字符串压缩算法实现 93. 字符串查找 94. 字符串去除前后空格 95. 实现模板引擎 96. 实现千位分隔符 97. 实现模板字符串解析功能 98. 实现一个函数判断数据类型 99. Promise 实现红绿灯交替 100. 实现节流函数(throttle) 101. 从指定数据源生成长度为 n 的不重复随机数组 102. 解析 URL Params 为对象 103. URL 验证 104. 判断括号字符串是否有效 105. 虚拟代理 106. 访问者模式 107. 版本号排序的方法

转化为驼峰命名

实现将字符串(如下划线、中划线命名)转换为驼峰命名格式的函数

问题

在前端开发中,我们经常需要处理不同的命名风格转换。例如将 CSS 中的 background-color、数据库字段的 user_name 等转换为 JavaScript 中常用的驼峰命名 backgroundColoruserName

需要实现一个函数,能够将各种分隔符命名(如下划线、中划线)转换为驼峰命名格式。

解答

/**
 * 转换为驼峰命名
 * @param {string} str - 需要转换的字符串
 * @param {boolean} isPascal - 是否转换为大驼峰(PascalCase),默认为小驼峰(camelCase)
 * @returns {string} 转换后的驼峰命名字符串
 */
function toCamelCase(str, isPascal = false) {
  if (!str || typeof str !== 'string') {
    return '';
  }

  // 使用正则匹配分隔符(-、_、空格等)及其后面的字符
  const result = str
    .replace(/[-_\s]+(.)?/g, (match, char) => {
      // 将分隔符后的字符转为大写
      return char ? char.toUpperCase() : '';
    })
    // 去除开头和结尾可能存在的分隔符
    .replace(/^[-_\s]+|[-_\s]+$/g, '');

  // 如果是大驼峰,首字母大写;否则首字母小写
  if (isPascal && result) {
    return result.charAt(0).toUpperCase() + result.slice(1);
  }
  
  return result.charAt(0).toLowerCase() + result.slice(1);
}

// 方法二:使用 split 和 map
function toCamelCase2(str, isPascal = false) {
  if (!str || typeof str !== 'string') {
    return '';
  }

  // 按分隔符分割字符串
  const words = str.split(/[-_\s]+/).filter(word => word.length > 0);
  
  if (words.length === 0) {
    return '';
  }

  // 处理每个单词
  const result = words.map((word, index) => {
    // 第一个单词根据 isPascal 决定是否首字母大写
    if (index === 0 && !isPascal) {
      return word.toLowerCase();
    }
    // 其他单词首字母大写
    return word.charAt(0).toUpperCase() + word.slice(1).toLowerCase();
  }).join('');

  return result;
}

使用示例

// 基本使用 - 小驼峰命名(camelCase)
console.log(toCamelCase('background-color'));        // backgroundColor
console.log(toCamelCase('user_name'));                // userName
console.log(toCamelCase('get-element-by-id'));       // getElementById
console.log(toCamelCase('hello_world_test'));        // helloWorldTest
console.log(toCamelCase('foo bar baz'));             // fooBarBaz

// 大驼峰命名(PascalCase)
console.log(toCamelCase('background-color', true));  // BackgroundColor
console.log(toCamelCase('user_name', true));         // UserName
console.log(toCamelCase('hello-world', true));       // HelloWorld

// 边界情况
console.log(toCamelCase(''));                        // ''
console.log(toCamelCase('single'));                  // single
console.log(toCamelCase('UPPER_CASE'));              // upperCase
console.log(toCamelCase('-leading-dash'));           // leadingDash
console.log(toCamelCase('trailing-dash-'));          // trailingDash
console.log(toCamelCase('multiple---dashes'));       // multipleDashes

// 使用方法二
console.log(toCamelCase2('background-color'));       // backgroundColor
console.log(toCamelCase2('user_name', true));        // UserName

关键点

  • 正则表达式匹配:使用 /[-_\s]+(.)?/g 匹配分隔符及其后面的字符,通过捕获组获取需要大写的字母

  • replace 回调函数:在 replace 的回调中,将分隔符后的字符转为大写,实现驼峰转换

  • 边界处理

    • 处理空字符串和非字符串输入
    • 去除首尾的分隔符
    • 处理连续多个分隔符的情况
  • 大小驼峰区分:通过 isPascal 参数控制首字母是否大写,实现 camelCase 和 PascalCase 的切换

  • 两种实现思路

    • 方法一:直接使用正则替换,代码简洁
    • 方法二:先分割再拼接,逻辑更清晰,易于理解和扩展
  • 性能考虑:对于大量转换操作,可以考虑添加缓存机制,避免重复计算相同字符串的转换结果