遍历整个<body>
标签内的文本节点,并对其中的违禁词进行替换,然后更新节点的文本内容。替换整个<body>
标签内出现的违禁词。
新建forbiddenWords.js文件
// 定义要替换的违禁词和替换文本
var forbiddenWords = ['违禁词1', '违禁词2'];
var replacementText = ' '; // 替换后的内容
// 递归函数:遍历元素及其子元素并替换违禁词
function replaceForbiddenWords(element) {
$(element).contents().each(function() {
// 判断当前节点类型
if (this.nodeType === Node.TEXT_NODE) {
// 替换违禁词
var originalText = this.textContent;
var replacedText = originalText;
$(forbiddenWords).each(function(index, word) {
replacedText = replacedText.replace(new RegExp(word, 'gi'), replacementText);
});
// 更新节点文本内容
if (replacedText !== originalText) {
this.textContent = replacedText;
}
} else if (this.nodeType === Node.ELEMENT_NODE) {
// 递归处理子元素
replaceForbiddenWords(this);
}
});
}
// 替换整个<body>标签内的违禁词
replaceForbiddenWords('body');
导入即可
<script src="forbiddenWords.js"></script>