Javascript / convert CSS style string into JS object

后端 未结 10 981
粉色の甜心
粉色の甜心 2021-01-04 08:41

We\'d like to convert a CSS style entered as string into a JS object.

E.g.,

 var input = \" border:solid 1px; color:red \";

expec

10条回答
  •  别那么骄傲
    2021-01-04 08:59

    something like this should get you pretty close:

    var input = " border:solid 1px; color:red ";
    var output = '{' + input.replace(/([\w-.]+)\s*:([^;]+);?/g, '\n    $1:"$2",') + '\n}';
    

    ...turns

    " border:solid 1px; color:red "
    

    into

    { 
        border:"solid 1px", 
        color:"red ",
    }
    

提交回复
热议问题