编辑代码

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);
// 输出: "MCV用户类型限制:不会通过Email渠道接收营销信息。"

const anotherString = "Customer type restriction: VIP user will not receive marketing messages via SMS channels.";
const anotherResult = replaceWithTranslation(anotherString);
console.log(anotherResult);
// 输出: "VIP用户类型限制:不会通过SMS渠道接收营销信息。"