[英]parse all content from HTML and find a string and replace But cannot replace tags string if match
我想解析HTML中的所有内容并找到一个字符串并替换,但是如果匹配则不能替换标签字符串。
我试过了,但是它也替换了标签名称,如类名。 但是我只想替换文字而不是标签名称或其他内容。
var toReplace = 'Hello';
var replaceWith ='Thank you';
document.body.innerHTML = document.body.innerHTML.replace(toReplace, replaceWith);
做这个:
<div id="container">
hello how are you <span class="hello">hello hello how are you</span>
</div>
<button onclick="myFunction();">Try it</button>
<script>
function myFunction()
{
var re = /(hello)(?![^<]*>|[<>]*<\/)/gm;
var str = document.getElementById("container").innerHTML;
var res = str.replace(re, 'thank you');
document.getElementById("container").innerHTML=res;
}
</script>
尝试这个。 :)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.