gpt4 book ai didi

javascript - 使用 JavaScript 将 kebab-case 转换为 camelCase

转载 作者:行者123 更新时间:2023-11-29 17:34:59 26 4
gpt4 key购买 nike

假设我有一个将 kebab-case 转换为 camelCase 的函数:

camelize("my-kebab-string") === 'myKebabString';

我快到了,但我的代码也输出大写的第一个字母:

function camelize(str){
let arr = str.split('-');
let capital = arr.map(item=> item.charAt(0).toUpperCase() + item.slice(1).toLowerCase());
let capitalString = capital.join("");

console.log(capitalString);
}

camelize("my-kebab-string");

最佳答案

您也可以尝试正则表达式。

camelize = s => s.replace(/-./g, x=>x[1].toUpperCase())

const camelize = s => s.replace(/-./g, x=>x[1].toUpperCase())
const words = ["stack-overflow","camel-case","alllowercase","allcapitalletters","custom-xml-parser","api-finder","json-response-data","person20-address","user-api20-endpoint"];
console.log(words.map(camelize));

仅查找后跟任何字符的连字符,并将其大写并用大写字符替换连字符+字符。

关于javascript - 使用 JavaScript 将 kebab-case 转换为 camelCase,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57556471/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com