图示:
本次小实例中需要用到正则表达式;匹配替换,用到replace
创建html文件demo.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>敏感词过滤</title>
</head>
<body>
<h2>敏感词过滤</h2>
<p>
<!-- 用户输入框 -->
<textarea name="" id="area" cols="30" rows="10"></textarea>
</p>
<p>
<!-- 点击提交 -->
<input type="submit" value="发布" id="input">
</p>
<!-- 进行展示 -->
<p id="res"></p>
</body>
</html>
<script>
//逻辑:用户输入的值,若正则匹配到了,则进行替换
//敏感词用*替换
//首先,通过Id先拿到这几个元素
let area = document.getElementById('area');
let input = document.getElementById('input');
let res = document.getElementById('res');
//正则匹配/..../,模式修饰符:g表示全局匹配
let reg = /笨蛋|脏话|滚/g;
input.onclick = function() {
//如果匹配到了reg的内容,就用*替换
let a = area.value.replace(reg, '*');
res.innerText = a;
console.log(a)
}
input
</script>
<style>
#res {
width: 200px;
height: 200px;
border: 1px solid #ccc;
}
</style>