regexmach

Regex for multidimensional input string name to get the the last number between quare brackets


Is there someone to help me with my regex?

I want to match always last integer suquare bracket for every string.

product[attribute][1][0][value] - In this case [0]
product[attribute][9871][56][value] - In this case [56]

Click here for My work:

/\[[0-9,-]+\]/g

The goal is to increment input name on clone, product[attribute][{attribute_id}][{clone_index}][value].


Solution

  • You may use

    var s = "product[attribute][1][0][value]";
    console.log(s.replace(
                /(.*\[)(\d+)(?=])/, function($0, $1, $2) { 
                   return $1 + (Number($2)+1);
                })
    )

    The regex matches

    Incrementing is done inside the callback method.