Search code examples
javascriptregexparentheses

Parse data between a function in javascript using regex


I have a string like the following

rotate(32) translate(0,-284.35468),translate(8545,84) matrix(d,f,g,s,g) translate(-58,88)

Each function can be separated by a comma or a blank space.

I want to find all the ocurrences of the information that is inside the brackets of "translate" using javascript regular expressions. So in the above example the desired result would be:

["0,-284.35468","8545,84","-58,88"]

To be more specific, I want to parse the information found in the "tranform" attribute of the "g" tag in the SVG specification. It can be found here http://www.w3.org/TR/2011/REC-SVG11-20110816/coords.html#TransformAttribute

Thank you


Solution

  • You can try a little something like this:

    var s = "rotate(32) translate(0,-284.35468),translate(8545,84) matrix(d,f,g,s,g) translate(-58,88)";
    
    var re = /translate\(([^,]+,[^)]+)\)/g,
        results = [],
        c;
    
    while (c = re.exec(s))
        results.push(c[1]);
    
    // results is now ["0,-284.35468", "8545,84", "-58,88"]
    

    Using the .exec() method repeatedly on a regex that has the "g" flag will find successive matches.

    In this case we're taking the second element in the array returned by .exec() since that will be the part of the string that matched the part of the regex in the capturing parentheses.