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

前端 未结 7 1290
情深已故
情深已故 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:15

    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()));

提交回复
热议问题