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

╄→尐↘猪︶ㄣ 提交于 2020-05-26 10:42:07

问题


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?


回答1:


You can use replace with a regex like:

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(/[A-Z]/g, m => "-" + m.toLowerCase()));
console.log("FooBar".replace(/[A-Z]/g, m => "-" + m.toLowerCase()));



回答2:


You can use replace() with regex. Then use toLowerCase()

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

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

`




回答3:


You can use https://github.com/epeli/underscore.string#dasherizestring--string from underscore.string library.




回答4:


Maybe you could use kebabCase from lodash: https://lodash.com/docs/4.17.15#kebabCase




回答5:


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`))



回答6:


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()}`)


来源:https://stackoverflow.com/questions/47836390/how-to-convert-a-camel-case-string-to-dashes-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!