如何替换txt='与'之间的MY_WORD?兼容多浏览器方案
仅替换
txt='...'范围内的MY_WORD为OTHER_WORD的兼容方案 需求场景
原始文本:
Some MY_WORD stupid txt='other text MY_WORD' and another MY_WORD stupid text and txt='something else MY_WORD' and also txt='here nothing to replace' and here txt='again to replace MY_WORD here'
需仅替换位于txt='和闭合'之间的MY_WORD为OTHER_WORD,保留外部的MY_WORD不变。
现有尝试的问题
- 使用后行断言的正则
/(?<=txt='.*)MY_WORD(?=.*')/g:
替换结果符合预期,但后行断言是ES2018新增特性,旧版浏览器(如IE、Chrome < 64、Firefox < 78)不支持,兼容性不足。 - 尝试的正则
(txt=')((\.*)(MY_WORD))?:
存在语法错误(\.*无意义,应为.*),且贪婪匹配+分组逻辑混乱,导致无法正确捕获目标内容。
可行解决方案
方案1:兼容所有浏览器的全局替换(支持单个txt块内多个MY_WORD)
利用replace的回调函数,先匹配完整的txt='...'块,再对块内内容单独替换:
const original = "Some MY_WORD stupid txt='other text MY_WORD' and another MY_WORD stupid text and txt='something else MY_WORD' and also txt='here nothing to replace' and here txt='again to replace MY_WORD here'"; const result = original.replace(/(txt='[^']*')/g, (match) => { return match.replace(/MY_WORD/g, 'OTHER_WORD'); });
替换后结果:
Some MY_WORD stupid txt='other text OTHER_WORD' and another MY_WORD stupid text and txt='something else OTHER_WORD' and also txt='here nothing to replace' and here txt='again to replace OTHER_WORD here'
逻辑说明:
/txt='[^']*'/g:全局匹配所有从txt='开始到第一个'结束的完整块([^']*匹配除单引号外的任意字符,避免跨块匹配)- 对每个匹配到的块,内部全局替换
MY_WORD为OTHER_WORD,外部内容完全不受影响
方案2:单次匹配替换(仅替换每个txt块内第一个MY_WORD)
如果仅需替换每个txt块内的第一个MY_WORD,可直接用捕获组替换:
const result = original.replace(/(txt='[^']*)(MY_WORD)([^']*')/g, '$1OTHER_WORD$3');
逻辑说明:
(txt='[^']*):捕获txt='到MY_WORD前的内容(MY_WORD):捕获目标替换字符串([^']*'):捕获MY_WORD到闭合'的内容- 替换时保留前后捕获内容,仅替换中间的
MY_WORD
内容的提问来源于stack exchange,提问作者user1182625
相关产品推荐
相关产品推荐

