Reputation: 21804
Here is an example CSS transform string:
rotate(-10 50 100)
translate(-36 45.5)
skewX(40)
scale(1 0.5)
From this string I want to either
How can I do this?
My best idea is to use RegEx, but I haven't figured out a working RegEx solution:
[a-z]+?\([\-a-z0-9\s]*?\)
https://regex101.com/r/Ycjuxz/1
You are also welcome to have a different idea for a solution that does not use RegEx.
Upvotes: 0
Views: 693
Reputation: 54011
A quick example of how you might do this using a regular expression and reducing the results down to an object:
function parseTransform(transform) {
return Array.from(transform.matchAll(/(\w+)\((.+?)\)/gm))
.reduce((agg, [, fn, val]) => ({
...agg,
[fn]: val
})
, {});
}
const res = parseTransform(`rotate(-10 50 100)
translate(-36 45.5)
skewX(40)
scale(1 0.5)`);
The output of this is
{rotate: "-10 50 100", translate: "-36 45.5", skewX: "40", scale: "1 0.5"}
In this version we overwrite the value of a function if it appears twice. You could merge them together if some properties can appear more than once.
Upvotes: 1
Reputation: 2046
Based on Teemu's comment:
const text=`rotate(-10 50 100)
translate(-36 45.5)
skewX(40)
scale(1 0.5)`;
const rows = text.split('\n');
const transformations = rows.reduce((acc, cur) => {
const key = cur.substring(0, cur.indexOf('('));
const value = cur.replace(key, '').replace('(', '').replace(')', '');
acc[key] = value;
return acc
}, {});
console.log(transformations);
Upvotes: 0