解析HTML中的所有内容并查找字符串并替换但是如果匹配则无法替换标记字符串

时间:2014-02-10 10:54:10

标签: javascript

我想解析HTML中的所有内容并查找字符串并替换但是如果匹配则无法替换标记字符串。

我尝试了这个,但它也替换了类名等标签内容。但我想只替换不是标签名称的文字。

var toReplace = 'Hello';
var replaceWith ='Thank you';
document.body.innerHTML = document.body.innerHTML.replace(toReplace, replaceWith);

1 个答案:

答案 0 :(得分:1)

这样做:

<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>

试试这个。 :)