web-dev-qa-db-ja.com

JavaScriptでキャメルケースの文字列をダッシュ​​に変換する方法は?

これらの文字列を変換したい:

fooBar
FooBar

に:

foo-bar
-foo-bar

JavaScriptでこれをどのように行うと、特定の文字列に対して最もエレガントでパフォーマンスの高い方法になりますか?

10
Timo

replaceは次のような正規表現で使用できます。

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

これはすべての大文字に一致し、"-"が前に付いた小文字に置き換えます。

例:

console.log("fooBar".replace(/[A-Z]/g, m => "-" + m.toLowerCase()));
console.log("FooBar".replace(/[A-Z]/g, m => "-" + m.toLowerCase()));
19
ibrahim mahrir

https://github.com/epeli/underscore.string#dasherizestring--string fromunderscore.stringを使用できます図書館。

2
jkordas

正規表現でreplace()を使用できます。次に、toLowerCase()を使用します

let camel = (s) => s.replace(/[A-Z]/g, '-$&').toLowerCase()

console.log(camel('fooBar'))
console.log(camel('FooBar'))

`

2

編集

単純なケース:

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

エッジケース:これは、1文字の極端なケースになる可能性があります。

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

たぶん、lodashからkebabCaseを使用できます: https://lodash.com/docs/4.17.15#kebabCase

0
Luci Furtun

あなたが使用することができます

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`))
0
Caio Santos