2

The following is my element id and I want to update it dynamically.

invoice[46][ap_details][4][ap_header_id]  

I want to update only second number, i.e. [4], like this:

invoice[46][ap_details][5][ap_header_id]

I am using below code which is updating both the values.

var strNewName = $(this).attr('name').replace(/\[\d+\]/g, function(strName) {
    strName = strName.replace(/[\[\]']+/g, '');
    var intNumber = parseInt(strName) + 1;
    return '[' + intNumber + ']';
});

Any help would be appreciated.

2
  • 1
    Can you tell us why? This may be optimized elsewhere! Commented Feb 14, 2017 at 13:36
  • maybe addClass / removeClass is a better way to go.. Commented Feb 14, 2017 at 14:11

3 Answers 3

1

var strName = "invoice[46][ap_details][4][ap_header_id]";

var parts = strName.split('[');
parts[3] = parts[3].replace(/^\d+/, n => +n + 1);

var strNewName = parts.join('[');
console.log(strNewName);

If you don't want to use arrow functions replace this line:

parts[3] = parts[3].replace(/^\d+/, n => +n + 1);

with this:

parts[3] = parts[3].replace(/^\d+/, function(n) { return +n + 1; });

Explanation:

split will return an array like this:

[
  "invoice",
  "46]",             // parts[1] to change this
  "ap_details]",
  "4]",              // parts[3] to change this (and so on, you do the math)
  "ap_header_id]"
]

The /^\d+/ will match any number at the begining (no need for the g modifier).

Replace with +n + 1 not n + 1 because n is a string, you have to force the interpretter to use it as a number or otherwise this "4" + 1 will result to this "41".

Then after you change what you want, join the parts using join with the same character you used for splitting ([).

Sign up to request clarification or add additional context in comments.

Comments

1

Using this regex /((\w)+)(\[\d+\])(\[(\w)+\])(\[\d+\])(\[(\w)+\])/gi you can construct the string back and change your integer.

var match = /((\w)+)(\[\d+\])(\[(\w)+\])(\[\d+\])(\[(\w)+\])/gi.exec(youString);
//group 6 is your digit.
var newId = parseInt(match[6].replace("\[\]", "")) + 1;
var newString = match[1] + match[3] + match[4] + "[" + newId + "]" + match[7];

Here is a fiddle with the answer https://jsfiddle.net/gzfud9vc/

Comments

1

Maybe dont use regex to build your element id. You can do its as follows as well:

var id = 5
var name = "invoice[46][ap_details][";
name += id;
name += "][ap_header_id]";

var toReplace = "invoice[46][ap_details][~~id~~][ap_header_id]"
var replaced = toReplace.replace(/~~id~~/g, id);

console.log(name);
console.log(replaced);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.