using javascript replace() to match the last occurance of a string
- by Dave
I'm building an 'add new row' function for product variations, and I'm struggling with the regex required to match the form attribute keys. So, I'm basically cloning rows, then incrementing the keys, like this (coffeescript):
newrow = oldrow.find('select, input, textarea').each ->
this.name = this.name.replace(/\[(\d+)\]/, (str, p1) ->
"[" + (parseInt(p1, 10) + 1) + "]"
)
this.id = this.id.replace(/\_(\d+)\_/, (str, p1) ->
"_" + (parseInt(p1, 10) + 1) + "_"
)
.end()
This correctly increments a field with a name of product[variations][1][name], turning it into product[variations][2][name]
BUT Each variation can have multiple options (eg, color can be red, blue, green), so I need to be able turn this product[variations][1][options][2][name] into product[variations][1][options][3][name], leaving the variation key alone. What regex do I need to match only the last occurrence of a key (the options key)?