Friday, May 17, 2024
 Popular · Latest · Hot · Upcoming
87
rated 0 times [  93] [ 6]  / answers: 1 / hits: 19189  / 12 Years ago, mon, may 14, 2012, 12:00:00

I have a form where the name attributes get updated, but the problem is im using multidimensional values as follows:



<input type=text name=questions[0][question] />
<input type=text name=questions[0][order] />
<input type=text name=questions[0][active] />
<input type=text name=answers[0][1][answer] />
<input type=text name=answers[0][2][answer] />
<input type=text name=answers[0][3][answer] />

<input type=text name=questions[1][question] />
<input type=text name=questions[1][order] />
<input type=text name=questions[1][active] />
etc...


I need to change the value within the square brackets with JavaScript no matter what position they are in.
I have tried using the following regular expression to match the value between the square brackets:



/(?<=[)[^]]*(?=])/g


but this matches all occurrences, and what I need to do is somehow find and replace the nth occurrence.



Or if there is another way to find and replace the values within the square brackets without using regular expressions I'm all ears.



Thanks in advance



Resolved



This final code is as follows:



$('input', this).each(function(){
var name = $(this).attr('name');
var i = 0;
$(this).attr('name', name.replace(/[.+?]/g,function (match, pos, original) {
i++;
return (i == 1) ? [THE REPLACED VALUE] : match;
}));
});

More From » jquery

 Answers
5

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


[#85592] Saturday, May 12, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
josiah

Total Points: 208
Total Questions: 105
Total Answers: 107

Location: Seychelles
Member since Mon, Jun 28, 2021
3 Years ago
;