js实现驼峰
实现字符串驼峰化的方法
使用正则表达式和字符串替换
通过正则表达式匹配字符串中的连字符或下划线,并将其后的字母转换为大写。移除所有非字母数字字符后,将首字母转为小写(小驼峰)或大写(大驼峰)。
function toCamelCase(str, isPascalCase = false) {
return str.replace(/[-_]+(.)?/g, (_, c) =>
c ? c.toUpperCase() : ''
).replace(/^./, firstChar =>
isPascalCase ? firstChar.toUpperCase() : firstChar.toLowerCase()
);
}
使用数组操作和字符转换
将字符串按分隔符拆分为数组,处理每个单词的首字母大小写后拼接成新字符串。
function toCamelCase(str, isPascalCase = false) {
const words = str.split(/[-_]/);
return words.map((word, i) =>
i === 0 && !isPascalCase
? word.toLowerCase()
: word.charAt(0).toUpperCase() + word.slice(1).toLowerCase()
).join('');
}
处理边界情况
空字符串或非字符串输入时返回原值,处理连续分隔符和数字开头的字符串。
function toCamelCase(str, isPascalCase = false) {
if (typeof str !== 'string') return str;
if (!str.trim()) return str;
return str
.replace(/^[^a-zA-Z]+/, '')
.replace(/[-_]+(.)?/g, (_, c) =>
c ? c.toUpperCase() : ''
)
.replace(/^./, firstChar =>
isPascalCase ? firstChar.toUpperCase() : firstChar.toLowerCase()
);
}
性能优化版本
对于长字符串处理,使用一次正则替换完成所有转换。
function toCamelCase(str, isPascalCase = false) {
return str.replace(
/(^|[-_])([a-z])/g,
(_, prefix, char) => char.toUpperCase()
).replace(/^./, firstChar =>
isPascalCase ? firstChar : firstChar.toLowerCase()
);
}
TypeScript 类型安全版本
添加类型注解确保输入输出类型正确。

function toCamelCase(str: string, isPascalCase: boolean = false): string {
return str.replace(/[-_]+(.)?/g, (_, c) =>
c ? c.toUpperCase() : ''
).replace(/^./, firstChar =>
isPascalCase ? firstChar.toUpperCase() : firstChar.toLowerCase()
);
}






