Answer the question
In order to leave comments, you need to log in
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);
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
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 questionAsk a Question
731 491 924 answers to any question