Given a style attribute string, I need to capture the x and y values of a CSS translate() property. Numbers may be zero, positive or negative, float or integer, and only of pixel units.
A practical style attribute string example:
min-height: 100%;
min-width: 100%;
transition-property: transform;
transform-origin: 0px 0px;
transform: translate(123px, 0px) translateZ(0px);
I have a working, albeit very ugly solution. Here’s a breakdown:
var transform = element.style['transform'] – transform variable then contains this string: "translate(123px, 0px) translateZ(0px)"
Then I match it against:
transform = transform.match(/translate\(-?[0-9]+(\.[0-9]*)?px, -?[0-9]+(\.[0-9]*)?px\)/);
I do this so if there’s another transform property, like rotate(20px, 20px) for example, I can avoid it.
The regex produces this array: ["translate(123px, 0px)", undefined, undefined].
Another regex is then in order, to match the numeric values only:
transform = transform[0].match(/(-?[0-9]+(\.[0-9]*)?)px, (-?[0-9]+(\.[0-9]*)?)px/);
Then I am left with the following array: ["123px, 0px", "123", undefined, "0", undefined]
And to finish everything I need to parseInt(transform[1]) and parseInt(transform[3]) to actually work with the values.
This seems like too much work for getting only those two numbers, but I am not very experienced with regular expressions, and I do not know how to streamline this. Is there a more elegant solution to this?
EDIT: I will particularly be happy to turn it all into a single regular expression 🙂
You can combine the two steps into one by doing something like the following:
or if you trust your input you can do:
to simplify your regex.