写一个方法把下划线命名转成大驼峰命名
function underlineToCamelCase(str) {
// 处理空字符串或非字符串的情况
if (typeof str !== 'string' || !str) {
return '';
}
return str.split('_').map((word, index) => {
// 首字母大写,其余小写
return index === 0
? word.charAt(0).toUpperCase() + word.slice(1).toLowerCase() // 第一个单词首字母也要大写
: word.charAt(0).toUpperCase() + word.slice(1).toLowerCase();
}).join('');
}
// 测试用例
console.log(underlineToCamelCase("hello_world")); // HelloWorld
console.log(underlineToCamelCase("one_two_three")); // OneTwoThree
console.log(underlineToCamelCase("user_name_info")); // UserNameInfo
console.log(underlineToCamelCase("_test")); // Test
console.log(underlineToCamelCase("test_")); // Test
console.log(underlineToCamelCase("")); // "" (空字符串)
console.log(underlineToCamelCase(null)); // "" (处理非字符串)
console.log(underlineToCamelCase(undefined)); // "" (处理非字符串)
console.log(underlineToCamelCase(123)); // "" (处理非字符串)
// 更简洁的写法 (使用replace方法和正则表达式)
function underlineToCamelCaseConcise(str) {
if (typeof str !== 'string' || !str) {
return '';
}
return str.replace(/_([a-z])/g, (match, group1) => group1.toUpperCase());
}
// 测试用例 (简洁写法)
console.log(underlineToCamelCaseConcise("hello_world")); // HelloWorld
console.log(underlineToCamelCaseConcise("one_two_three")); // OneTwoThree
console.log(underlineToCamelCaseConcise("user_name_info")); // UserNameInfo
console.log(underlineToCamelCaseConcise("_test")); // _test (开头下划线保留)
console.log(underlineToCamelCaseConcise("test_")); // test_ (结尾下划线保留)
console.log(underlineToCamelCaseConcise("")); // "" (空字符串)
console.log(underlineToCamelCaseConcise(null)); // "" (处理非字符串)
console.log(underlineToCamelCaseConcise(undefined)); // "" (处理非字符串)
console.log(underlineToCamelCaseConcise(123)); // "" (处理非字符串)
两种方法的比较:
underlineToCamelCase
: 更易理解,逐个单词处理,并且能处理开头或结尾是下划线的情况。underlineToCamelCaseConcise
: 更简洁,使用正则表达式一步到位,但开头或结尾的下划线会被保留。 如果需要处理开头结尾的下划线,需要额外处理。
根据实际需求选择合适的方法。 如果需要处理开头或结尾的下划线,建议使用第一种方法或修改第二种方法增加对开头结尾下划线的处理。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· winform 绘制太阳,地球,月球 运作规律
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)