Leo Jiang
Leo Jiang

Reputation: 26105

Converting JS camelcase DOM style properties into valid CSS properties?

I want to take any camelcase property on CSSStyleDeclaration and get the corresponding kebabcase CSS property. E.g. converting marginLeft to margin-left. Is there a built-in function that does this? I don't want to simply convert camelcase into kebabcase because there's no guarantee that it'll always work.

Upvotes: 1

Views: 905

Answers (1)

maziyank
maziyank

Reputation: 616

Function using regex:

function CamelToSnake(string) {
    return string.replace(/([a-z]|(?=[A-Z]))([A-Z])/g, '$1-$2').toLowerCase();
};

CamelToSnake("marginLeft")

Upvotes: 4

Related Questions