Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 697
Henrik Avatar asked Nov 27 '22 20:11

Henrik


2 Answers

Try the following:

var result = "fooBarBaz".replace(/([A-Z])/g, "-$1").toLowerCase(); 
console.log(result);
like image 68
Patrik Oldsberg Avatar answered Mar 23 '23 00:03

Patrik Oldsberg


var res = yourString.replace(/[A-Z]/g, "-$&").toLowerCase(); 
like image 36
zx81 Avatar answered Mar 22 '23 23:03

zx81