<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title></title>
    <script type="text/javascript">
      window.onload = function() {
        //普通方式
        // var pt = document.querySelector('input');
        // var p = document.querySelector('p');
        // pt.onkeyup = function(e) {
        //  var ev = window.event || e;
        //  if (ev.keyCode == 13) {
        //    var sens = /测试内容|和谐|疫情/g;
        //    var txt = pt.value;
        //    if (sens.test(txt)) {
        //      p.innerText = txt.replace(sens, '***');
        //      sens.lastIndex = 0; //调整记号 下次匹配还从头开始
        //    } else {
        //      p.innerText = txt;
        //    }
        //  }
        // }
        //'敏感词' 如果加全局匹配 就会出现下一次匹配接着上一次匹配的末尾进行的bug
        //解决bug的办法1:不加g
        //解决bug的方法2:我们就可以把记号重新调整到下标0 
        //调整方法: 正则表达式.lastIndex = 0;
        //面向对象
        function Sensitive(){
          this.pt = document.querySelector('input');
          this.p = document.querySelector('p');
          this.init();
          // console.log(this.pt,this.p)
        }
        Sensitive.prototype.init = function(){
          var that = this;
          //按下键盘
          this.pt.onkeyup = function(e){
            var ev = window.event || e;
            that.up(ev);
          }
        }
        Sensitive.prototype.up = function(ev){
          // console.log(ev) 
          // keyCode: 13 enter
          if(ev.keyCode == 13){
            var txt = this.pt.value;
            //设置正则
            var sens = /测试内容|和谐|疫情/g;
            //替换敏感内容
            this.p.innerHTML = txt.replace(sens,function(a){
              return a.replace(/./g,'*');
            })
          }
        }
        new Sensitive();
      }
    </script>
  </head>
  <body>
    <input type="text" value="测试内容" placeholder="请输入敏感词汇" />
    <p></p>
  </body>
</html>
