In my current task, I'm animating the coordinates of SVG paths, so I'm trying to programmatically alter their values depending on an offset that the user changes. The coordinates are in ugly attributes whose values looks something like this:
M0,383c63,0,89.3,-14.1,117.4,-65.9...
For an offset of 100, the new value might need to look something like:
M0,483c63,0,89.3,-14.1,217.4,-65.9... // without the bold (it's just there to highlight diff)
I pass in different regular expressions for different paths, which look something like, say, /long(N)and...N...ugly(N)regex/
, but each path has a different amount of captures (I can pass in that quantity too). Using the answers here and a loop, I figured out how to programmatically make an array of newly changed values (regardless of the number of captures), giving me something like ['483','217.4',...]
.
My question is, how do I programmatically replace/inject the altered numbers back into the string (as in the line above with the bolded numbers)?
My workaround for the moment (and a fiddle):
I'm generating a "reverse" regex by switching parens around, which ends up looking like /(long)N(and...N...ugly)N(regex)/
. Then I'm doing stuff by hand, e.g.:
if (previouslyCapturedCount == 3) {
d = d.replace(reverseRE, "$1" + dValuesAltered[0] + "$2" + dValuesAltered[1] + "$3" + dValuesAltered[2] + "$4");
} else if (previouslyCapturedCount == 4) {
// and so on ...
But there's gotta be a better way, no? (Maybe due to my lack of JS skillz, I simply wasn't able to extrapolate it from the answers in the above linked question.)
Caveat: There are several questions here on S.O. that seem to answer how to do multiple replacements on specific pairs, but they seem to assume global replacements, and I have no guarantee that the matched/captured numbers will be unique in the string.