用户jquery通用地将一个单词替换为另一个单词,但忽略html标签,属性,脚本标签等



我想在整个dom中用另一个单词"firm"替换一个单词说"strong"。 但是,我想确保这只替换文本,而不是在 html 标签或脚本标签内。

<span> He was strong </span>应替换为<span>He was firm </span><strong> He was strong </strong>不应替换为<firm>He was firm </firm>,而应替换为<strong> He was firm </strong>

它也不应该在 html 属性或脚本标签中替换它

<script>
var strong= 2;
<script>

法典

const html = jQuery(document.body).html();

var re = new RegExp("\b"+word+"\b","g");
const replaced = html.replace(re, replacement);
jQuery(document.body).html(replaced);

我正在考虑使用正则表达式来确定内容何时在 html 中,但不确定这是否是一个好主意。

正则表达式匹配开放标签,但 XHTML 自包含标签除外

总结一下:需要用另一个单词替换一个单词的所有实例,而不在脚本标签、html 标签等中这样做。

您可以尝试以下代码吗?$('*').each(function(index, element) { var newtext=$(element).text().replace("strong","firm"); $(element).text(newtext); });

最新更新