I have a textarea (with id ‘work’) with successive numbers in square brackets as follows:
[6] [7] [8] [9] [10]
I want that on pressing a button, each of these should increase by 1, like this:
[7] [8] [9] [10] [11]
How do I do this in Javascript? I wrote the following, but it does not work:
addOne = function() {
var work = document.getElementById('work');
var re = /\[\d+\]/g
var arr = re.match(work.value);
var len = arr.length;
var pat = /\d+/
var begin = pat.exec(arr[0]);
var last = pat.exec(arr[len-1]);
for (i=begin;i<=last;i++) {
var re1 = new RegExp("[i]");
var re2 = new RegExp("[i++]");
var newval = work.value.replace(re1,re2);
work.value = newval;
}
}
The textarea may also have other text apart from these numbers. Please help me here.
Any guidance will be appreciated.
I’d use
.replacein conjunction with a RegExp and a callback function (demo: http://jsfiddle.net/veYTt/):I used
++i, because++iconvertsifrom a string to a number, and returns the valuei + 1. An alternative is(i + 1*1).Explanation of the RegExp:
\[matches[.(\d+)matches and captures any integer. This group is passed to the callback function as a second argument, which I namedi.(?=\])is a look-ahead. It causes the pattern to match when the previously matched characters are followed by].