Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

regex - Parse SVG transform attribute with javascript

Supposing we have an SVG transform string:

transform = "translate(6,5),scale(3,3)";

Is there a slick regex function we could use to parse that into something usable?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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' ]
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...