using javascript replace() to match the last occurance of a string

Posted by Dave on Stack Overflow See other posts from Stack Overflow or by Dave
Published on 2014-08-23T16:09:51Z Indexed on 2014/08/23 16:20 UTC
Read the original article Hit count: 226

Filed under:
|
|

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)?

© Stack Overflow or respective owner

Related posts about JavaScript

Related posts about regex