本文介绍如何使用JavaScript结合正则表达式在页面中实现敏感词的自动屏蔽功能。通过定义包含敏感词的规则,利用replace方法将匹配内容替换为指定字符,从而在用户输入或展示文本时自动过滤敏感信息,保障页面内容安全。
JavaScript敏感词过滤实现
本文介绍一种利用JavaScript在网页上自动屏蔽敏感词的实现方案,供读者参考使用。
<html>
<head>
<title>Bad Words Example</title>
<script type="text/javascript">
function filterText(sText) {
var reBadWords = /badword|anotherbadword/gi;
return sText.replace(reBadWords, "****");
}
function showText() {
var oInput1 = document.getElementById("txt1");
var oInput2 = document.getElementById("txt2");
oInput2.value = filterText(oInput1.value);
}
</script>
</head>
<body>
<P>
<textarea rows="10" cols="50" id="txt1">badword anotherbadword</textarea><br />
<input type="button" value="Filter Bad Words" onclick="showText()" /></p>
<P>Filtered Text:<br />
<textarea rows="10" cols="50" id="txt2"></textarea></p>
</body>
</html>
希望这段关于JavaScript程序设计的代码示例能为您提供帮助。