Search code examples
javascriptstringcamelcasing

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?


Solution

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