javascriptjsonregexecmascript-5

How to replace multiple regex matches in a JSON object


Given a JSON object which contains tags identified by {{, I need to find all matches in the payload and replace them. The following code works, but only returns the 1st match, and if I turn on the gim flags to replace all matches, the code breaks. It is worth noting that the application uses ECMA5 engine (SpiderMonkey)

For the sake of demoing, I'm using the window variables, as with the application I am working for, I should also be replacing with workflow variables, so works similarly.

var Obj = {
  hostname: "Test 1 {{window.location.hostname}}",
  protocol: "Test 2 {{window.location.protocol}}"
}
var myObj   = JSON.stringify(Obj)
var regex   = /\{\{window\.location\.(.+?)\}\}/       //gmi flag breaks code
var match   = myObj.match(regex)[1];
var enrich  = Function('return '+"window.location."+match)();
var _Obj    = myObj.replace(regex,enrich)


console.log(JSON.parse(_Obj))

The regex works as follows (https://regex101.com/r/BPFnKK/1) I am using index [1] to select the value.

enter image description here


Solution

  • There's no need to use the Function constructor for this. When you use a callback function as the replacement, it receives the capture group values as arguments, and can use them in the substitution.

    var Obj = {
      hostname: "Test 1 {{window.location.hostname}}",
      protocol: "Test 2 {{window.location.protocol}}"
    }
    
    var myObj = JSON.stringify(Obj);
    var _Obj = myObj.replace(/\{\{window\.location\.(.+?)\}\}/g, function(match, g1) { return window.location[g1];});
    
    console.log(JSON.parse(_Obj))