问题描述
说我有一个将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");
要保留您现有的代码,我刚刚在索引上添加了一个检查,如果item为0,则该索引将返回item
而不是转换后的项目(错误),因为问题就在于您也对第一个项目使用了大写字母,而您不应该这样做.
(item, index) => index ? item.charAt(0).toUpperCase() + item.slice(1).toLowerCase() : item
,因为:- 如果index不是伪造的(因此,如果您的上下文中index> 0),则返回大写的字符串.
- 否则,将返回当前项目.
当然,这可能更整洁,并且可能是单行,但是我想尽可能地靠近您的代码,以便您了解错误所在:
function camelize(str){
let arr = str.split('-');
let capital = arr.map((item, index) => index ? item.charAt(0).toUpperCase() + item.slice(1).toLowerCase() : item);
// ^-- change here.
let capitalString = capital.join("");
console.log(capitalString);
}
camelize("my-kebab-string");
作为旁注,您可以在此处找到一个更干净的潜在答案:转换骆驼案中的任何字符串
Say I have a function that transforms kebab-case
to camelCase
:
camelize("my-kebab-string") == 'myKebabString';
I'm almost there, but my code outputs the first letter with uppercase too:
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");
To keep your existing code, I've just added a check on the index that will return item
instead of the transformed item if item is 0 (falsy), since the problem is just that you are upper-casing the first item as well, while you shouldn't.
In a nutshell, the inline expression becomes: (item, index) => index ? item.charAt(0).toUpperCase() + item.slice(1).toLowerCase() : item
, because:
- If index is not falsy (so, if index is > 0 in your context), the capitalized string is returned.
- Otherwise, the current item is returned.
Of course, this could be cleaner and likely single line, but I wanted to stay as close as possible to your code so that you could understand what was wrong:
function camelize(str){
let arr = str.split('-');
let capital = arr.map((item, index) => index ? item.charAt(0).toUpperCase() + item.slice(1).toLowerCase() : item);
// ^-- change here.
let capitalString = capital.join("");
console.log(capitalString);
}
camelize("my-kebab-string");
As a side note, you could've found a potential cleaner answer here: Converting any string into camel case
这篇关于将kebab-case转换为camelCase-Javascript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!