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

前端 未结 7 1274
情深已故
情深已故 2021-02-13 02:22

I want to convert these strings:

fooBar
FooBar

into:

foo-bar
-foo-bar

How would I do this in JavaScript the m

7条回答
  •  情话喂你
    2021-02-13 03:10

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

提交回复
热议问题