Note that there are some explanatory texts on larger screens.

plurals
  1. POFind and replace nth occurrence of [bracketed] expression in string
    text
    copied!<p>I have a form where the <strong>name attributes get updated</strong>, but the problem is im using multidimensional values as follows:</p> <pre><code>&lt;input type="text" name="questions[0][question]" /&gt; &lt;input type="text" name="questions[0][order]" /&gt; &lt;input type="text" name="questions[0][active]" /&gt; &lt;input type="text" name="answers[0][1][answer]" /&gt; &lt;input type="text" name="answers[0][2][answer]" /&gt; &lt;input type="text" name="answers[0][3][answer]" /&gt; &lt;input type="text" name="questions[1][question]" /&gt; &lt;input type="text" name="questions[1][order]" /&gt; &lt;input type="text" name="questions[1][active]" /&gt; etc... </code></pre> <p>I need to change the value within the square brackets with JavaScript no <strong>matter what position</strong> they are in. I have tried using the following regular expression to match the value between the square brackets: </p> <pre><code>/(?&lt;=\[)[^\]]*(?=\])/g </code></pre> <p>but this matches all occurrences, and what I need to do is somehow find and replace the nth occurrence.</p> <p>Or if there is another way to find and replace the values within the square brackets without using regular expressions I'm all ears.</p> <p>Thanks in advance</p> <p><strong>Resolved</strong></p> <p>This final code is as follows:</p> <pre><code>$('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; })); }); </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload