I have a string
var oldName = "questions[0].answers[3].answer";
I want to increment the the answers part to [4]( +1 of what the current value is). If it is questions[0].answers[6].answer
it should become questions[0].answers[7].answer.
I tried with the following but I am not getting any result.
var matches = oldName.match(/(\d+)answers(\d+)/)
var number1 = Number(matches[1]);
var number2 = Number(matches[2]);
I need to store the numbers in the string in 2 separate variables.
It is simple to do this, just supply a replacement function to String.replace
:
str.replace(/answers\[(\d+)\]/, function (_, $1) {
return "answers[" + (+$1 + 1) + "]";
});
(If you want an explanation on the parameters to the replacement function, you can read the MDN link above, or my answer here )
But whether this is a good solution to the bigger problem, I don't know.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.