Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert enum (as string) from CAPS_CASE to camelCase

I've found a solution to convert an ENUM to camelCase, but it's not elegant.

var underscoreToCamelCase = function(str) {
    str = (str === undefined || str === null) ? '' : str;
    str = str.replace(/_/g, " ").toLowerCase();
    return str.replace(/(?:^\w|[A-Z]|\b\w|\s+)/g, function(match, index) {
        if (+match === 0) return "";
        return index == 0 ? match.toLowerCase() : match.toUpperCase();
    });
}

So, if str is MY_ENUM_STRING it will return myEnumString.

There must be a way to achieve this with a single regex match?

like image 280
Matthew Trow Avatar asked Jan 24 '26 17:01

Matthew Trow


1 Answers

Try this:

var underscoreToCamelCase = function(str) {

  return str.toLowerCase()
    .replace(/_+(\w|$)/g, function ($$, $1) {
        return $1.toUpperCase();
    });

}
like image 161
CD.. Avatar answered Jan 26 '26 07:01

CD..



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!