Henrik
Henrik

Reputation: 703

How to change camelCase to slug-case (or kabob-case) via regex in JavaScript

For some reason, this answer I found for (supposedly) how to do it in php just gives me the wrong matches. It seems to add the dash, but also replace the capital letter with a copy of the remainder of the string, so I want "abcZxc" to turn into "abc-zxc", but instead it turns it into "abd-zxczxc"

This, plus a bunch of other variations, is what I've tried, but can't get it to work.

filterGroup = aNiceString;
console.log(filterGroup.replace(/[A-Z]+/g, "-1$'"))

Thanks

Upvotes: 4

Views: 10061

Answers (3)

Mathias Brodala
Mathias Brodala

Reputation: 6460

Another variant which splits into an array which is joined again right away, this avoids the leading -:

let result = "FooBarBaz.".match(/[A-Z][a-z]*/g).join('-').toLowerCase();
console.log(result);

Upvotes: 1

Patrik Oldsberg
Patrik Oldsberg

Reputation: 1550

Try the following:

var result = "fooBarBaz".replace(/([A-Z])/g, "-$1").toLowerCase(); 
console.log(result);

Upvotes: 25

zx81
zx81

Reputation: 41838

var res = yourString.replace(/[A-Z]/g, "-$&").toLowerCase(); 

Upvotes: 2

Related Questions