Jose Miguel Ledón
Jose Miguel Ledón

Reputation: 309

reg ex expression to find and replace a number inside []

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

Answers (3)

Dominique Fortin
Dominique Fortin

Reputation: 2238

var name = $(this).attr("name");
var num = 1 + (1*name.replace(/.*\[(\d+)\].*/, "$1"));
$(this).attr("name",name.replace(/\[(\d+)\]/, "["+num+"]"));

Upvotes: 0

Akshat Mahajan
Akshat Mahajan

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

Carson Ip
Carson Ip

Reputation: 1946

Use String.replace(). ref: MDN

var name = "sale[sales_details_attributes][123][tax]";
var str = name.replace(/\[(\d+)\]/,function(match, p1){
    return "[" + (parseInt(p1,10) + 1) + "]";
});
alert(str);

Upvotes: 0

Related Questions