js留言板过滤敏感词案例

<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
* {
margin: 0;
padding: 0;

}

#d1 {
width: 630px;
height: 420px;
background: orange;
margin-top: 50px;
margin-left: 300px;

}

#d2 {
width: 530px;
height: 358px;
/* background: yellow; */
margin-left: 50px;
margin-top: 5px;
}

#d2 ul {
width: 100%;
height: 100%;
background: olivedrab;
}

ul,
li {
list-style: none;
}

ul li {
width: 100%;
height: 50px;
background: yellow;
float: left;
font-size: 25px;
margin-top: 10px;
opacity: 0.7;
}


#number {
width: 456px;
height: 50px;
margin-left: 50px;
float: left;
margin-top: 5px;
}

#but {
width: 70px;
height: 54px;
float: left;
margin-top: 5px;
}
</style>
<!-- <script src="./common.js"></script> -->
<script>
window.onload = function () {
var number = document.getElementById("number");//获取元素
var u1 = document.getElementById("u1");
var a1 = document.getElementById("a1");

var arr = ["我的中国心", "长江长城", "黄山黄河"];//将需要渲染的数据存到数组中
function xuanran() {//渲染函数

var html = arr.map(function (item, i) {//遍历数组 并给一个编号(下标)
//console.log(item);
return `<li>${i + 1}.${item} </li>`//渲染输出的格式

}).join("");//转换成字符串

u1.innerHTML = html;//写入到元素中

}
xuanran();//调用

function filter(str) {//过滤敏感词
var arr1 = ["fuck", "妈蛋", "操", "反清复明", "金三胖", "去死", "MMP"];//可添加其他敏感词
arr1.forEach(function (item) {//遍历敏感词数组
var reg = new RegExp(item, 'gi'); // 正则表达式将输入的每一个元素进行筛选
str = str.replace(reg, '***');//将在敏感词数组的数据替换成***
});
return str;//返回
}


function creat() {//添加内容
var num = number.value;//获取输入的数据
var a = filter(num);//过滤敏感词
arr.unshift(a);//添加到数组最前
//console.log(arr);//存到数组
if (arr.length > 5) {//因为页面只显示5个 所以要限制长度
arr.pop();//从后面删除
}
xuanran();//重新渲染 因为数组中的内容变了

number.value = "";// 渲染后将元素的输入框清空
number.focus();//聚焦
}

but.onclick = function () {//点击事件
creat();//调用
}
number.onkeydown = function (ev) {//键盘enter触发
if (ev.keyCode == 13) {//判断键值是否为13,enter的键值=13;
creat();//调用
}
}
}


</script>
</head>

<body>
<div id="d1">
<div id="d2">
<ul id=u1></ul>
</div>
<input type="text" id="number">
<input type="button" id="but" value="确定">
</div>
</body>

</html>

猜你喜欢

转载自www.cnblogs.com/sun-shine1229/p/10653992.html