写一个方法把下划线命名转成大驼峰命名
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: 更简洁,使用正则表达式一步到位,但开头或结尾的下划线会被保留。 如果需要处理开头结尾的下划线,需要额外处理。
根据实际需求选择合适的方法。 如果需要处理开头或结尾的下划线,建议使用第一种方法或修改第二种方法增加对开头结尾下划线的处理。
浙公网安备 33010602011771号