Home > Net >  Javascript Regex replace token content, included token
Javascript Regex replace token content, included token

Time:06-23

i'm trying to make this test work, but i'm not able to get the proper REGEX:

test.only("Should replace text in brackets by variables in data", () => {
  let text: string = "This is some [name] in a [entryDate]";
  const _data: RequestData = [{ name: "Test" }, { entryDate: "12/12/2022" }];

  _data.forEach((param) => {
    const key = Object.keys(param)[0];
    const pattern = new RegExp(/[\[\]'] /g);
    console.log(pattern);
    text = text.replace(pattern, param[key]);
  });
  expect(text).toContain("This is some Test in a 12/12/2022");
});

It's kinda self-explanatory but I need that

"This is some [name] in a [entryDate]"

to be

"This is some Test in a 12/12/2022"

my best try, at the moment, with the above regex is:

Expected substring: "This is some Test in a 12/12/2022"
Received string:    "This is some TestnameTest in a TestentryDateTest"

Thanks!

CodePudding user response:

Convert the data first to a single, plain object, and then iterate the placeholders in the string:

let text = "This is some [name] in a [entryDate]";
const _data = [{name: "Test"}, {entryDate: "12/12/2022"}];

const dict = Object.fromEntries(_data.flatMap(Object.entries));

text = text.replace(/\[(.*?)\]/g, (match, key) => dict[key] ?? match);

console.log(text);

  • Related