Javascript Regex替换标记内容,包含标记



我正试图使此测试工作,但我无法获得适当的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");
});

这是不言自明的,但我需要它

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

"This is some Test in a 12/12/2022"
我最好的尝试,目前,上面的正则表达式是:
Expected substring: "This is some Test in a 12/12/2022"
Received string:    "This is some TestnameTest in a TestentryDateTest"

谢谢!

首先将数据转换为单个普通对象,然后迭代字符串中的占位符:

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);

最新更新