Z
Z
zeni1agent2020-03-08 14:05:24
css
zeni1agent, 2020-03-08 14:05:24

How to turn a string with styles into an object?

Need to convert a string

width:100px;  height:100px; background:red;  transform-origin: 100% 0%; transform:  translate(100px, 100px)  scale(1, 0.5) skew(30deg, 20deg) rotate(1deg);

into an object
var arr = {
'width': '100px',
'height': '100px',
'background': 'red',
'transform-origin' : ['100%' ,  '0%']
'transform': {
'translate': ['100px', '100px'],
'scale': [ '1',  '0.5'],
'skew': ['30deg', '20deg'],
'rotate': '1deg'
}
};

Answer the question

In order to leave comments, you need to log in

2 answer(s)
E
Eugene Chefranov, 2019-07-28
@Arhangel_one

0
0xD34F, 2020-03-08
@zeni1agent

const parseValue = str => {
  const values = str.match(/[^\s,]+/g) || [ null ];
  return values.length > 1 ? values : values[0];
};

const parseStyleStr = str =>
  str.split(';').reduce((acc, n) => {
    const [ k, v ] = n.split(':').map(n => n.trim());
    if (k && v) {
      const f = [...v.matchAll(/([\w]+?)\((.+?)\)/g)];
      acc[k] = f.length
        ? Object.fromEntries(f.map(n => [ n[1], parseValue(n[2]) ]))
        : parseValue(v);
    }

    return acc;
  }, {});

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question