JavaScript如何用正则匹配2个目标片段并替换为span标签实现高亮?
多目标词汇正则替换高亮span失效修复方案
需求说明
- 给文本内指定目标词汇包裹带样式的
<span>标签,实现高亮效果 - 预期匹配2处不同的目标文本,分别包裹span标签
- 实际运行仅第一处匹配内容能正常替换,第二处不生效
问题代码
let regex = /make your life easier|forget about the “I have to’s”/gi, let aboutUsText3: "We have more than 10 years’ experience in the sector and can offer you a professional and comprehensive real estate service. We’re here to [make your life easier], so that you can forget about the [“I have to’s”]. We can give you advice on whatever you need, whether it’s refurbishments, interior design, decoration, rental management, valuation of investments, or anything else. We’re here for you.", const spannedText2 = locale === "es" ? es.aboutUsText3 : aboutUsText3.replace( regex.t3, [ `<span class="fw-bold text-span">${strEnToSpan[2]} </span>`, `<span class="fw-bold text-span">${strEnToSpan[3]}</span>`, ].shift() );
错误原因
- 核心逻辑错误:
String.replace的第二个参数传入的是数组执行shift()后的返回值,shift()仅在代码初始化时执行1次,取数组第一个元素作为固定替换值,后续所有匹配项都会复用这个值,无法为第二个匹配项返回对应的span模板 - 引用错误:定义的正则变量名为
regex,替换时调用的是不存在的regex.t3属性 - 匹配遗漏:原始文本的目标词汇外层包裹了方括号
[],现有正则未覆盖带方括号的匹配场景 - 基础语法错误:变量定义时缺失赋值符号、存在多余逗号,代码本身存在运行异常
修正后代码
// 定义匹配规则,可灵活新增高亮词汇 const highlightRules = [ { match: /\[?make your life easier\]?/gi, template: `<span class="fw-bold text-span">${strEnToSpan[2]}</span>` }, { match: /\[?“I have to’s”\]?/gi, template: `<span class="fw-bold text-span">${strEnToSpan[3]}</span>` } ] const aboutUsText3 = "We have more than 10 years’ experience in the sector and can offer you a professional and comprehensive real estate service. We’re here to [make your life easier], so that you can forget about the [“I have to’s”]. We can give you advice on whatever you need, whether it’s refurbishments, interior design, decoration, rental management, valuation of investments, or anything else. We’re here for you." let spannedText2 = locale === "es" ? es.aboutUsText3 : aboutUsText3 // 遍历规则依次替换 highlightRules.forEach(rule => { spannedText2 = spannedText2.replace(rule.match, rule.template) })
预期输出效果
替换完成后文本符合要求,两处目标词汇均被正确包裹高亮标签:
<p>We have more than 10 years’ experience in the sector and can offer you a professional and comprehensive real estate service. We’re here to <span class="bold">make your life easier</span>, so that you can forget about the <span class="bold">“I have to’s”</span>. We can give you advice on whatever you need, whether it’s refurbishments, interior design, decoration, rental management, valuation of investments, or anything else. We’re here for you.</p>
内容的提问来源于stack exchange,提问作者Leo
相关产品推荐
相关产品推荐

