You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

加密Web应用字符连锁替换异常求助:错误替换衍生字符

解决文本加密/解密中的连锁替换问题

问题根源

你的代码出现连锁替换的核心原因是:

  • 加密时,循环执行replace会让新替换生成的字符被后续的替换规则再次处理(比如a→ai后,新生成的i又被i→imes替换)。
  • 解密时不仅存在同样的连锁问题,还存在defaultDiacriticsReturnMap里重复的"ober"键,且替换顺序不合理(短匹配项会优先破坏长匹配项)。

修复方案

1. 加密逻辑优化

改用一次性匹配所有需要替换的原始字符,通过正则的|组合匹配项,并用回调函数完成替换,确保每个原始字符仅被处理一次,不会触发连锁替换。

2. 解密逻辑优化

  • 移除defaultDiacriticsReturnMap中的重复键;
  • 按匹配字符串长度从长到短排序替换规则,避免短匹配项提前破坏长匹配项(比如先替换enter再替换ai,防止enter里的片段被误处理);
  • 同样使用一次性正则匹配+回调替换的方式,避免连锁替换。

修改后的完整代码

/* 加密逻辑 */
const defaultEncryptMap = {
    "a": "ai",
    "e": "enter",
    "i": "imes",
    "o": "ober",
    "u": "ufat"
};

// 生成匹配所有原始字符的正则,开启全局匹配
const encryptRegex = new RegExp(Object.keys(defaultEncryptMap).join('|'), 'g');

function encryptText(str) {
    // 回调函数直接替换匹配到的原始字符,不会处理新生成的内容
    return str.replace(encryptRegex, match => defaultEncryptMap[match]);
}

function replaceText() {
    const str = document.getElementById('original-text').value;
    document.getElementById('result-text').value = encryptText(str);
}

/* 解密逻辑 */
const defaultDecryptMap = {
    "ai": "a",
    "enter": "e",
    "imes": "i",
    "ober": "o",
    "ufat": "u"
};

// 按匹配字符串长度从长到短排序,避免短匹配优先破坏长匹配项
const sortedDecryptKeys = Object.keys(defaultDecryptMap).sort((a, b) => b.length - a.length);
const decryptRegex = new RegExp(sortedDecryptKeys.join('|'), 'g');

function decryptText(str) {
    return str.replace(decryptRegex, match => defaultDecryptMap[match]);
}

function returnText() {
    const str = document.getElementById('original-text').value;
    document.getElementById('result-text').value = decryptText(str);
}

/* 复制文本逻辑 */
function copyText() {
    const copyText = document.getElementById("result-text");
    copyText.select();
    copyText.setSelectionRange(0, 99999);
    navigator.clipboard.writeText(copyText.value);
    alert("Copied the text: " + copyText.value);
}
<textarea id="original-text"></textarea>
<button onclick="replaceText()">Encrypt text</button>
<button onclick="returnText()">Decrypt text</button>
<textarea id="result-text"></textarea>
<button onclick="copyText()">Copy text</button>

测试验证

  • 输入aeiou加密后会得到aienterimesoberufat,无连锁替换;
  • 将加密结果输入解密,会正确还原为aeiou。

内容的提问来源于stack exchange,提问作者IvanTenryu

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.04 13:45:24