Reputation: 309
I have an input like this:
<input type="hidden" value="0.0" name ="sale[sales_details_attributes][1][tax]">
and I want to increment the [1] to [2] (i'll not know if there's a 1 or 2 or whatever, this is just for example) inside name attribute, it can be made with a regex expression but i cant make it work i tried this:
var name = $(this).attr("name").replace("[?(\d+)?\]", "[2]");
there's a way to get the 1 and make an increment by 1 using regex?
Upvotes: 0
Views: 55
Reputation: 2238
var name = $(this).attr("name");
var num = 1 + (1*name.replace(/.*\[(\d+)\].*/, "$1"));
$(this).attr("name",name.replace(/\[(\d+)\]/, "["+num+"]"));
Upvotes: 0
Reputation: 9846
The best way to do it is to extract the number as a string, convert it to a number, and then use toString()
in conjunction with replace
.
var input_string = "sale[sales_details_attributes][3434][tax]";
var number = Number(input_string.match(/(\d+)/)[0]);
input_string.replace(number.toString(), (number+1).toString())
This should work for most numbers. However, it assumes there is only one instance of a number in your input_string
.
Upvotes: 2