function generateTemplateKey(template) {
return template.replace(/\${(\w+)}/g, '${var}');
}
function extractVariables(template) {
const matches = template.match(/\${(\w+)}/g);
return matches ? matches.map(match => match.slice(2, -1)) : [];
}
function replaceWithTranslation(currentString) {
for (const [key, { original, translation }] of reverseTemplateMap) {
const regex = new RegExp('^' + key.replace(/\${var}/g, '(.+?)') + '$');
const match = currentString.match(regex);
if (match) {
let result = translation;
const variables = extractVariables(original);
variables.forEach((variable, index) => {
result = result.replace(`\${${variable}}`, match[index + 1]);
});
return result;
}
}
return currentString;
}
const templateMap = new Map();
templateMap.set(
"Customer type restriction: ${userType} user will not receive marketing messages via ${channelTipsText} channels.",
"${userType}用户类型限制:不会通过${channelTipsText}渠道接收营销信息。"
);
const reverseTemplateMap = new Map();
templateMap.forEach((translation, original) => {
const key = generateTemplateKey(original);
reverseTemplateMap.set(key, { original, translation });
});
const currentString = "Customer type restriction: MCV user will not receive marketing messages via Email channels.";
const result = replaceWithTranslation(currentString);
console.log(result);
const anotherString = "Customer type restriction: VIP user will not receive marketing messages via SMS channels.";
const anotherResult = replaceWithTranslation(anotherString);
console.log(anotherResult);