如何使用 Javascript 有选择地替换下面文本中名为 Rindan 的单词, 但如果它在某些属性中,如 img alt=="Rindan" 我想替换 Rindans 这个词,它是一个内部文本,而不是在属性中。
`"<a href="http://edition.cnn.com/video/?hpt=hp_t1#/video/bestoftv/2012/02/28/ac-marie-rindan-family-syria.cnn">Rindan's family on her legacy</a> <a href="http://edition.cnn.com/video/?hpt=hp_t1#/video/bestoftv/2012/02/28/ac-marie-Rindan-family-syria.cnn" target=""><img alt="Rindan's family on her legacy" border="0" class="cnnVideoIcon" height="10" src="http://i.cdn.turner.com/cnn/.e/img/3.0/global/icons/video_icon.gif" width="16" /></a>`"
最佳答案
可以在字符串的replace
函数中使用函数参数
your_string = your_string.replace(<regexp>,
function(matched, index){
// check matched
return replacement;
});
});
引用:https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String/replace
关于Javascript 替换 innerText 而不是它的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9478069/