JavaScript RegExp to CamelCase a hyphened CSS property

后端 未结 6 1201
心在旅途
心在旅途 2021-02-19 12:47

I am trying to change CSS properties like this one.

-moz-border-radius

To the JavaScript CSS property like so.

MozBorderRadius
         


        
6条回答
  •  礼貌的吻别
    2021-02-19 13:24

    if you need to convert an entire object of hypen-delimited keys to camelCase:

    const css2js = (obj) => Object.fromEntries(Object.entries(obj).map(x => [x[0].replace(/(-)([a-z])/g, c => c[1].toUpperCase()), x[1]]));
    

    example

    const a = {
        "background-color": "#00aa",
        marginTop: "10px"
    };
    
    console.log(css2js(a)); // {backgroundColor: "#00aa", marginTop: "10px"}
    

    https://codepen.io/oriadam/pen/eYBNeyP

提交回复
热议问题