简体   繁体   English

使用 JavaScript 将 kebab-case 转换为 camelCase

[英]Convert kebab-case to camelCase with JavaScript

Say I have a function that transforms kebab-case to camelCase :假设我有一个将kebab-case转换为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");

You can also try regex.您也可以尝试正则表达式。

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

Looks only for hyphen followed by any character, and capitalises it and replaces the hyphen+character with the capitalised character.仅查找后跟任何字符的连字符,并将其大写并将连字符+字符替换为大写字符。

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.为了保留您现有的代码,我刚刚添加了对索引的检查,如果 item 为 0(假),它将返回item而不是转换后的 item,因为问题只是您将第一个 item 大写,而你不应该。

In a nutshell, the inline expression becomes: (item, index) => index ? item.charAt(0).toUpperCase() + item.slice(1).toLowerCase() : item简而言之,内联表达式变为: (item, index) => index ? item.charAt(0).toUpperCase() + item.slice(1).toLowerCase() : item (item, index) => index ? item.charAt(0).toUpperCase() + item.slice(1).toLowerCase() : item , because: (item, index) => index ? item.charAt(0).toUpperCase() + item.slice(1).toLowerCase() : item ,因为:

  • If index is not falsy (so, if index is > 0 in your context), the capitalized string is returned.如果 index 不是 falsy(因此,如果 index 在您的上下文中 > 0),则返回大写字符串。
  • 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.toLowerCase()); // ^-- 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作为旁注,您可以在这里找到一个潜在的更清晰的答案: 将任何字符串转换为驼峰式

对于lodash用户:

_.camelCase('my-kebab-string') => 'myKebabString'

The first method is to just transform to lower case the first entry of your capital array, like this:第一种方法是将capital数组的第一个条目转换为小写,如下所示:

capital[0] = capital[0].toLowerCase();

Another method, which I think to be more efficient, is to pass another parameter to the map callback, which is the index .另一种我认为效率更高的方法是将另一个参数传递给map回调,即index Take a look at this for further reading: https://www.w3schools.com/jsref/jsref_map.asp看看这个以进一步阅读: https ://www.w3schools.com/jsref/jsref_map.asp

So you transform to upper case only if (index > 0) .因此,仅if (index > 0)时才转换为大写。 Like this:像这样:

let capital = arr.map((item, index) => index ? item.charAt(0).toUpperCase() + item.slice(1).toLowerCase() : item);

so I tried both array-string and regex but regex is slower !所以我尝试了数组字符串和正则表达式,但正则表达式更慢!

 const string = " background-color: red; \n color: red;\n z-index: 10" // regex console.time("regex") let property = string const camelProp = property.replace(/(-[az])/, (g) => { return g.replace("-", "").toUpperCase() }) console.timeEnd("regex") // custom console.time("custom") const str = string let strNew = str .split("-") .map((e) => { return e[0].toUpperCase() + e.slice(1) }) .join("") console.timeEnd("custom") console.log(camelProp) console.log(strNew)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 camelCase 到 kebab-case - camelCase to kebab-case 如何在camelCase PascalCase snake_case kebab-case (JS) 之间进行转换 - How to convert between camelCase PascalCase snake_case kebab-case (JS) 在 css-loader 3.4.2 中通过 localsConvention 将 kebab-case 转换为 camelCase 不工作 - kebab-case to camelCase via localsConvention in css-loader 3.4.2 not working 如何在 Vue 中使用 kebab-case 命名组件? - How can I use kebab-case for naming components in Vue? 我如何将烤肉架装入PascalCase? - How do I covert kebab-case into PascalCase? VueJS v-bind无法使用kebab-case - VueJS v-bind not working with kebab-case 在 JavaScript 中将“Sentence case”转换为“camelCase” - Convert "Sentence case" to "camelCase" in JavaScript 使用 Next js 时在 CSS/SASS 模块中使用 kebab-case CSS 类名 - Using kebab-case CSS classnames in CSS/SASS modules when using Next js React 样式:Wrapper 组件生成`不支持将 kebab-case 用于对象中的 css 属性。 您是说 ariaLabel?` 错误 - React styled: Wrapper component produces `Using kebab-case for css properties in objects is not supported. Did you mean ariaLabel?` error 为什么允许使用 kebab-case 非标准属性,而不允许使用其他属性? 以及如何在 TypeScript 中定义这样的类型? - Why kebab-case non-standard attributes are allowed while others aren't? And how to define types like this in TypeScript?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM