3

I have string array like following:

{ customer:2046 } bought a product { product:6473 }

{ customer:2046 } bought a product { product:5243 }

{ customer:37 } bought a product { product:6333 } to { customer:1501 }

If I just initialize the regexp outside the loop, some of the array will be skipped mapping, like these:

Peter bought a product chair

{ customer:2046 } bought a product { product:5243 }

John bought a product table to Susan

I have to add regexp at 2nd place so all array will be mapped? What's goes wrong?

    let activities = [];   
    var tkRegex = /{\s*(?:customer):(\d+)\s*}/g;        
    var pfRegex = /{\s*(?:product):(\d+)\s*}/g;
    activities = dActivities.map((act, key) => {                  
      if(act.hasOwnProperty('task_id')){
        let task = dTasks.find(el => el.id === act.task_id);        
        if(task){
          let matches = tkRegex.exec(act.template)
          if (matches && matches[1] == act.task_id) {
            act.template = act.template.replace(matches[0], task.name);                
          }
        }
      }
      // tkRegex = /{\s*(?:customer):(\d+)\s*}/g;        
      // pfRegex = /{\s*(?:product):(\d+)\s*}/g;
      // Why do I have to assign the value here again so the regexp works 
      as I expect?
      if(act.hasOwnProperty('profile_ids')){
        act.profile_ids.map((pId, key) => {
          let pf = dProfiles.find(el => el.id === pId);
          if(pf){
            let matches = pfRegex.exec(act.template);                
            if (matches && matches[1] == pId) {
              act.template = act.template.replace(matches[0], pf.abbreviated_name);
            }                
          }              
        });
      }
      return act.template;
    });
MIT
  • 109
  • 1
  • 7

0 Answers0