编写姓名转camelCase格式的函数:现有函数无法适配大写开头的lastName
修复姓名转camelCase格式的函数问题
现有代码在处理姓氏(lastName)首字母大写的场景时失效,比如传入'john', 'SMITH'时无法得到正确的johnSmith。
问题根源
原代码中,lastName.toLowerCase().replace(lastName[0], lastName[0].toUpperCase())的逻辑存在漏洞:当原始姓氏首字母为大写(如'SMITH'),转小写后的字符串是'smith',此时用原始首字母'S'去替换,找不到匹配项,导致姓氏部分始终是全小写,无法生成首字母大写的格式。
正确实现方案
方案一:拆分首字母与剩余字符处理
const toCamelCase = function(firstName, lastName) { // 名字全部转小写 const normalizedFirstName = firstName.toLowerCase(); // 姓氏首字母大写,其余部分转小写 const normalizedLastName = lastName.charAt(0).toUpperCase() + lastName.slice(1).toLowerCase(); const camelCaseName = normalizedFirstName + normalizedLastName; console.log(camelCaseName); return camelCaseName; }; // 测试用例 toCamelCase('albert', 'einstein'); // 输出 albertEinstein toCamelCase('MR', 'beast'); // 输出 mrBeast toCamelCase('john', 'SMITH'); // 输出 johnSmith
方案二:正则表达式统一处理
const toCamelCase = function(firstName, lastName) { const normalizedFirstName = firstName.toLowerCase(); // 正则匹配首字母转为大写,剩余字符转为小写 const normalizedLastName = lastName.replace(/(^.)(.*)/, (_, firstChar, restChars) => { return firstChar.toUpperCase() + restChars.toLowerCase(); }); const camelCaseName = normalizedFirstName + normalizedLastName; console.log(camelCaseName); return camelCaseName; }; // 测试用例 toCamelCase('albert', 'einstein'); // 输出 albertEinstein toCamelCase('MR', 'beast'); // 输出 mrBeast toCamelCase('john', 'SMITH'); // 输出 johnSmith
这两种方案都能稳定处理各种大小写组合的姓名输入,确保输出符合camelCase规范:名字全小写,姓氏首字母大写、其余小写,两者拼接。
内容的提问来源于stack exchange,提问作者Petri Heva
相关产品推荐
相关产品推荐

