This question already has an answer here: Replace text but not the HTML tags?(1个答案)5年前关闭。假设我有一个HTML字符串var _str = <div>The European languages are members of the same family. <div class="same">Their separate existence is a myth.</div> For science, music, sport, etc, Europe uses the same vocabulary. The languages only differ in their grammar, <div class="same">their pronunciation and their most common words.</div></div>我想将文本same替换为<span class="highlighted">same</span>我在做_str.replace('same', '<span class="highlighted">same</span>');所以它也将class="same"替换为class="<span class="highlighted">same</span>"有谁能帮助我如何只替换文本而不替换节点()中的任何内容吗? (adsbygoogle = window.adsbygoogle || []).push({}); 最佳答案 一个简单的解决方案是在“same”之前添加一个空格,如下所示:_str.replace(' same', ' <span class="highlighted">same</span>'); (adsbygoogle = window.adsbygoogle || []).push({}); 09-25 21:25