简体   繁体   English

Javascript替换innerText而不是它的属性

[英]Javascript to replace innerText and not if its an attribute

如何使用 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> &nbsp;<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>`"

Give the id to a block, get the innerHTML, and use the replace string function:将 id 赋予一个块,获取innerHTML,并使用替换字符串函数:

var get=document.getElementById('test');
var str=get.innerHTML;
document.write(str.replace("Rindan's","TestNAme"));

set this back to innerHTML将此设置回innerHTML

see live demo on http://jsfiddle.net/kunalvashist/CeeDU/http://jsfiddle.net/kunalvashist/CeeDU/上查看现场演示

You can use the function parameter in replace function of string您可以在字符串的replace函数中使用函数参数

your_string = your_string.replace(<regexp>,  
     function(matched, index){
        // check matched 
        return replacement;
     }); 
}); 

ref: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String/replace参考: https : //developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String/replace

this is to replace the text and not the attributes:这是替换文本而不是属性:

var aa = document.getElementsByTagName('a');
for(i=0;i<=aa.length;i++)
{
aa[i].innerText = aa[i].innerText.replace("Rindan","anyone");
}
​

You could loop all children elements of the body tag and do a replace on the innerhtml.您可以循环 body 标记的所有子元素并在 innerhtml 上进行替换。

var body_children = document.body.children;
for(var i = 0; i < body_children.length; i++){
   var str = body_children[i].innerHTML
   body_children[i].innerHTML = str.replace("this","with this");
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM