-2

I am trying to iterate over a list of dicts(keys:labelname and id) and want to get the string after the label value using regex

text = "Company Name: ABC \n Address: 123St, LA \n Post Code: 12345 \n"
const itemList = [
  { id: 'companyName', label: 'Case or Reference Id' },
  { id: 'companyaddress', label: 'Address' },
  { id: 'companyPostcode', label: 'Post Code' }
];
for (let i = 0; i < itemList.length; i++) {
      let caseRegex = /(?<=${itemList[i].label}: )\w+/g;
      let regexStr = caseRegex.exec(text);
      console.log("regexStr",regexStr);
};

It works when I try the string as it is. But I not able to get the above work using variable from loop

for (let i = 0; i < itemList.length; i++) {
      let caseRegex = /(?<=Company Name: )\w+/g;
      let regexStr = caseRegex.exec(text);
      console.log("regexStr",regexStr);
};
ttt
  • 1
  • 2

1 Answers1

-1

Use the RegExp constructor to create a dynamic regular expression. You can use a template literal to interpolate variables into the string.

let caseRegex = new RegExp(`(?<=${itemList[i].label}: )\w+`, 'g');

Note that you may need to escape regular expression metacharacters when constructing the RegExp.

Unmitigated
  • 76,500
  • 11
  • 62
  • 80