Search code examples
javascriptcssregexcss-transforms

Extract the different css transformations from a transform string?


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

  • get one string for each transformation
  • get an object with properties I can access

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.


Solution

  • 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.