我有类似的东西:
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'
我想用
MY_WORD
替换 OTHER_WORD
,但前提是它位于 txt='
和 '
内部
/(?<=txt='.*)MY_WORD(?=.*')/g
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 hexe txt='again to replace OTHER_WORD here'
但是并非所有浏览器都支持向后查找,因此这不是一个好方法。
A 尝试过这个,但即使它说有组匹配,我 3 美元是空的。
(txt=')((\.*)(MY_WORD))?
您可以使用一个简单的状态机来搜索和替换内部引号,这允许多次替换,并且不依赖于您所说的正则表达式,由于某种原因在感兴趣的浏览器中没有很好地支持:
const str = "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 and MY_WORD again '";
function replaceWordInQuotes(str, word, replace){
const len = word.length;
let insideQuotes = false, quoteIdx = 0;
const found = [];
while(true){
const i = str.indexOf("'", quoteIdx);
if(i < 0) break;
if(insideQuotes){
const wi = str.indexOf(word, quoteIdx);
if(wi < 0) break;
if(wi < i){
found.push(wi);
quoteIdx = wi + len;
continue;
}
}
insideQuotes = !insideQuotes;
quoteIdx = i + 1;
}
console.log('found indices:', ...found);
let result = '', prev = 0;
for(const i of found){
result += str.slice(prev, i) + replace;
prev = i + len;
}
result += str.slice(prev);
return result;
}
console.log(replaceWordInQuotes(str, 'MY_WORD', 'OTHER_WORD'));
您可以使用捕获组:
const str = "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 = str.replace(/('[^']*)(?:MY_WORD)([^']*')/g, '$1OTHER_WORD$2');
console.log(result);