Skip to content

Instantly share code, notes, and snippets.

@stekhn
Last active November 24, 2022 08:56
Show Gist options
  • Save stekhn/b767bfce1565cb53e3cdb091ff169ab5 to your computer and use it in GitHub Desktop.
Save stekhn/b767bfce1565cb53e3cdb091ff169ab5 to your computer and use it in GitHub Desktop.
Parse the individual values from the CSS/SVG transform attribute into an object with RegEx and serialize them back into a string
// Adapted from https://stackoverflow.com/a/17838403/2037629
// If possible, use getComputedStyle() instead: https://stackoverflow.com/a/64654744/2037629
type TransformValues = {
translate?: string[];
rotate?: string[];
scale?: string[];
};
export const parseTransform = (string: string) => {
const groups: TransformValues = {};
const values = string.match(/(\w+)\(([^,)]+),?([^)]+)?\)/gi);
for (const index in values) {
const keys = values![index as any].match(/[\w\.\-]+/g);
if (keys && keys.length) {
groups[keys?.shift() as keyof typeof groups] = keys;
}
}
return groups;
};
// Usage: parseTransform("translate(25,978) rotate(90deg) scale(2)")
// Output: { translate: [ "25", "978" ], rotate: [ "90deg" ], scale: [ "2" ] }
export const serializeTransform = (array: TransformValues) =>
Object.keys(array)
.map((key) => `${key}(${array[key as keyof typeof array]})`)
.join(" ");
// Usage: serializeTransform({ translate: [ "25", "978" ], rotate: [ "90deg" ], scale: [ "2" ] })
// Output: "translate(25,978) rotate(90deg) scale(2)"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment