Parse SVG transform attribute with javascript
Assuming you are running in a browser, you could also use the SVG DOM to parse and decode the transform string.
var svgns = "http://www.w3.org/2000/svg";
function getTransformList(transformStr)
{
// Create a fake <rect> element to set the transform to
var rect = document.createElementNS(svgns, "rect");
rect.setAttribute("transform", transformStr);
// Use the DOM to get the list of decoded transforms
dumpTransform(rect.transform.baseVal);
}
function dumpTransform(transformList)
{
for (var i = 0; i < transformList.numberOfItems; i++)
{
var transform = transformList.getItem(i);
var m = transform.matrix;
switch (transform.type)
{
case 2:
console.log("translate("+m.e+","+m.f+")");
break;
case 3:
console.log("scale("+m.a+","+m.d+")");
break;
case 4:
console.log("rotate("+transform.angle+")");
// TODO need to also handle rotate(angle, x, y) form
break;
case 5:
// TODO skewX()
break;
case 6:
// TODO skewY(()
break;
case 1:
default:
console.log("matrix("+m.a+","+m.b+","+m.c+","+m.d+","+m.e+","+m.f+")");
break;
}
}
}
getTransformList("translate(6,5),scale(3,3)");
Adapted from @chernjie's solution:
function parse_transform(a) {
var b = {};
for (var i in a = a.match(/(\w+)\(([^,)]+),?([^)]+)?\)/gi)) {
var c = a[i].match(/[\w\.\-]+/g);
b[c.shift()] = c;
}
return b;
}
Here's a nifty little snippet of code that might get you what you need, it should cover most scenario in case the string you intend to parse has different number of arguments:
function parse (a)
{
var b={};
for (var i in a = a.match(/(\w+\((\-?\d+\.?\d*e?\-?\d*,?)+\))+/g))
{
var c = a[i].match(/[\w\.\-]+/g);
b[c.shift()] = c;
}
return b;
}
Running this
parse('translate(6,5),scale(3,3.5),a(1,1),b(2,23,-34),c(300)');
Will result in this:
{
translate: [ '6', '5' ],
scale: [ '3', '3.5' ],
a: [ '1', '1' ],
b: [ '2', '23', '-34' ],
c: [ '300' ]
}