简体   繁体   English

如何在 JavaScript 中将驼峰式字符串转换为破折号?

[英]How to convert a camel-case string to dashes in JavaScript?

I want to convert these strings:我想转换这些字符串:

fooBar
FooBar

into:进入:

foo-bar
-foo-bar

How would I do this in JavaScript the most elegant and performant way for any given string?对于任何给定的字符串,我将如何在 JavaScript 中以最优雅、最高效的方式执行此操作?

You can use replace with a regex like:您可以使用带有正则表达式的replace ,例如:

let dashed = camel.replace(/[A-Z]/g, m => "-" + m.toLowerCase());

which matches all uppercased letters and replace them with their lowercased versions preceded by "-" .它匹配所有大写字母,并将它们替换为以"-"开头的小写版本。

Example:例子:

 console.log("fooBar".replace(/[AZ]/g, m => "-" + m.toLowerCase())); console.log("FooBar".replace(/[AZ]/g, m => "-" + m.toLowerCase()));

也许你可以使用kebabCase的 kebabCase: https ://lodash.com/docs/4.17.15#kebabCase

You can use replace() with regex.您可以将replace()与正则表达式一起使用。 Then use toLowerCase()然后使用toLowerCase()

 let camel = (s) => s.replace(/[AZ]/g, '-$&').toLowerCase() console.log(camel('fooBar')) console.log(camel('FooBar'))

` `

对于那些不需要前面连字符的人:

 console.log ("CamelCase".replace(/[AZ]/g, (match, offset) => (offset > 0 ? '-' : '') + match.toLowerCase()))

您可以使用来自underscore.string库的https://github.com/epeli/underscore.string#dasherizestring--string

EDIT编辑

Simple case:简单案例:

"fooBar".replace( /([a-z])([A-Z])/g, '$1-$2' ).toLowerCase();   
"FooBar".replace( /([a-z])([A-Z])/g, '$1-$2' ).toLowerCase();

Edge case: this can get an extreme case where you have a single char.极端情况:这可能是一个极端情况,您只有一个字符。

"FooBarAFooBar".replace(/([A-Z])/g, (g) => `-${g[0].toLowerCase()}`)

You can use您可以使用

const makeItDashed = camelCased => {
   let dashed = ``
   camelCased.split(``).map(ch => {{dashed += ch.toUpperCase() == ch ? `-${ch.toLowerCase()}` : ch}})
   return dashed
}

console.log(makeItDashed(`fooBar`))
console.log(makeItDashed(`FooBar`))

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM