代码:
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>敏感词过滤</title> 6 <style type = "text/css"> 7 #msg { 8 400px; 9 height: 200px; 10 background: gold; 11 border: 1px solid black; 12 } 13 14 </style> 15 <script> 16 window.onload = function(){ 17 var oBtn = document.getElementById("btn1"); //获取文档节点button 18 var oTxt = document.getElementById("txt1"); //获取文档节点textarea 19 var oDiv = document.getElementById("msg"); //获取文档节点div 20 var arr = [/TMD/ig, /垃圾/ig, /靠/ig, /尼玛/ig, /垃圾/ig, /艹/ig];//敏感词数组 通过正则表达式全局匹配,不区分大小写。 21 oBtn.onclick = function(){ 22 var str = oTxt.value;//获取用户输入字符串 23 for(var i = 0; i < arr.length; i++){ 24 var str = str.replace(arr[i], '*');//将替换后的字符串继续付给str。 25 } 26 oDiv.innerHTML = str;//将过滤后的字符串在div中输入 27 oTxt.value = '';//清空发布框里的内容 28 } 29 30 } 31 32 </script> 33 </head> 34 <body> 35 <textarea id = "txt1" rows = "10" cols = "50"></textarea> 36 <button id = "btn1">发布</button> 37 <div id = "msg"></div> 38 </body> 39 </html>
效果图: