Find and Replace all occurrences of a phrase in a json string using capturing groups
<p>I have a stringified JSON which looks like this:</p>

<p>...</p>

<pre><code>"message":null,"elementId:["xyz1","l9ie","xyz1"]}}]}], "startIndex":"1", 
"transitionTime":"3","sourceId":"xyz1","isLocked":false,"autoplay":false
,"mutevideo":false,"loopvideo":false,"soundonhover":false,"videoCntrlVisibility":0,
...,"elementId:["dgff","xyz1","jkh90"]}}]}]
</code></pre>

<p>... it goes on.</p>

<p>The part I need to work on is the value of the <code>elementId</code> key. (The 2nd key in the first line, and the last key).</p>

<p>This key is present in multiple places in the JSON string. The value of this key is an array containing 4-character ids.</p>

<p>I need to replace one of these ids with a new one.</p>

<p>The kernel of the idea is something like:</p>

<pre><code>var elemId = 'xyz1' // for instance
var regex = new RegExp(elemId, 'g');
var newString = jsonString.replace(regex, newRandomId);
jsonString = newString;
</code></pre>

<p>There are a couple of problems with this approach. The regex will match the id anywhere in the JSON. I need a regex which only matches it inside the elementId array; and nowhere else.</p>

<p>I'm trying to use a capturing group to match just the occurrences I need, but I can't quite crack it. I have:</p>

<pre><code>/.*elementId":\[".*(xyz1).*"\]}}]/
</code></pre>

<p>But this doesn't match the 1st occurence of 'xyz1 in the array.</p>

<p>So, <strong>firstly, I need a regex which can match all the 'xyz1's inside elementId; but nowhere else</strong>. The sequence of square and curly brackets after elementId ends doesn't change anywhere in the string, if that helps.</p>

<p>Secondly, even if I have a capturing group that works, <code>string.replace</code> doesn't act as expected. Instead of replacing just the match inside the capturing group, it replaces the whole match.</p>

<p>So, my second requirement is <strong>replacing only the captured groups, not the whole match.</strong></p>

<p>What a need is a piece of js code which will replace my 'xyz1's where needed and return the following string (assuming the newRandomId is 'abcd'):</p>

<pre><code>"message":null,"elementId:["abcd","l9ie","abcd"]}}]}], "startIndex":"1", 
"transitionTime":"3","sourceId":"xyz1","isLocked":false,"autoplay":false
,"mutevideo":false,"loopvideo":false,"soundonhover":false,"videoCntrlVisibility":0,
...,"elementId:["dgff","abcd","jkh9"]}}]}]
</code></pre>

<p>Note that the value of 'sourceId' is unaffected.</p>

<p>EDIT: I have to work with the JSON. I can't parse it and work with the object since I don't know all the places the old id might be in the object and looping through it multiple times (for multiple elements) would be time-consuming</p>