I have a form where the name attributes get updated, but the problem is im using multidimensional values as follows:
The approach given in the accepted answer is concise and solid, but it has a drawback: if there's a big string with a lot of appearances of the given substring, it will be scanned till the end - even if one has to replace only at the beginning. The alternative would be using 'exec', then breaking off the chain right after the replacement is done:
function replaceNthOccurence(source, pattern, replacement, n) {
var substr = '';
while (substr = pattern.exec(source)) {
if (--n === 0) {
source = source.slice(0, substr.index) + replacement + source.slice(pattern.lastIndex);
break;
}
}
return source;
}
console.log( replaceNthOccurence('bla_111_bla_222_bla_333', /\d+/g, '1st', 1) );
console.log( replaceNthOccurence('bla_111_bla_222_bla_333', /\d+/g, '2nd', 2) );
console.log( replaceNthOccurence('bla_111_bla_222_bla_333', /\d+/g, '3rd', 3) );
Here is another possible solution. You can pass the string.replace function a function to determine what the replacement value should be. The function will be passed three arguments. The first argument is the matching text, the second argument is the position within the original string, and the third argument is the original string.
The following example will replace the second "L" in "HELLO, WORLD" with "M".
var s = "HELLO, WORLD!";
var nth = 0;
s = s.replace(/L/g, function (match, i, original) {
nth++;
return (nth === 2) ? "M" : match;
});
alert(s); // "HELMO, WORLD!";
See MDN: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String/replace
If I understand the question correctly the RegExp shown below should do:
var patt = /<input.*?(\[(\d)\])(\[(\d)\]){0,1}.*/g
var res = patt.exec(' <input type="text" name="questions[0][1][question]" />');
alert('First number: ' + res[2] + "\nSecond number: " + res[4]);
Demo here: http://jsfiddle.net/EUcdX/