如何实现完整短语优先替换,避免替换短语内的单个单词?
解决短语缩写替换的优先级问题
当前代码的核心问题是:短短语会被优先替换,导致包含该短短语的长短语无法被正确匹配。比如输入"mobile telephone number"时,"Telephone"先被替换成TEL,剩下的内容就没法匹配"Mobile telephone number"这个长短语了。
通用解决方案:优先替换长短语
要解决这个问题,关键是让长短语先被匹配替换,避免短短语提前破坏长短语的结构。具体步骤如下:
- 提取字典中所有的短语-缩写配对
- 按短语长度从长到短排序
- 按排序后的顺序依次执行替换操作
修改后的代码
JavaScript 部分
let dictionary = { "M": { "Mobile telephone number": "M/TEL" }, "T": { "Telephone": "TEL" } }; function abbreviateText() { const input = document.getElementById("input").value; let output = input; // 把字典里的所有短语和缩写整理成数组 const phraseList = []; for (const group in dictionary) { for (const phrase in dictionary[group]) { phraseList.push({ full: phrase, short: dictionary[group][phrase] }); } } // 按短语长度降序排序,长短语先处理 phraseList.sort((a, b) => b.full.length - a.full.length); // 遍历执行替换 phraseList.forEach(item => { // 转义短语中的正则特殊字符,避免语法错误 const safePhrase = item.full.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); const regex = new RegExp(`\\b${safePhrase}\\b`, "gi"); const tooltipSpan = `<span class="tooltip" data-tooltip="${item.full}">${item.short}</span>`; output = output.replace(regex, tooltipSpan); }); document.getElementById("output").innerHTML = output; }
HTML 部分(无需修改)
<textarea id="input" placeholder="Enter message" rows="7" oninput="abbreviateText()"></textarea> <p id="output"></p>
关键细节说明
- 排序逻辑:通过
b.full.length - a.full.length实现降序排序,确保长短语优先被匹配,从根本上避免短短语提前替换的问题。 - 正则转义:添加
safePhrase处理,防止短语中包含.、?等正则特殊字符导致匹配失败,让代码更健壮。 - 兼容性:不管字典有多少分组、多少短语,这个逻辑都能自动处理优先级,是通用的解决方案。
测试输入"mobile telephone number"时,会直接匹配长短语替换成<span class="tooltip" data-tooltip="Mobile telephone number">M/TEL</span>,完全符合预期。
内容的提问来源于stack exchange,提问作者Niyaz
相关产品推荐
相关产品推荐

