js利用replace方法去除敏感字符(俗称的 河蟹!!!)

<!DOCTYPE HTML>
<html>
    <head>
        <title>please enter your title</title>
        <meta charset="utf-8">
        <meta name="Author" content="年轻人">
        <style type='text/css'> *{ font-family:'Microsoft yahei'; } </style>
    </head>
    <body>

        <input type="text" id="txt" /> <input type="button" id="btn" value="留言" />
        <div id="box"></div>

        <script type="text/javascript"> var oTxt = document.getElementById('txt'); var oBtn = document.getElementById('btn'); var oBox = document.getElementById('box'); var reg = /傻逼|垃圾|你大爷/g; oBtn.onclick = function(){ var val = oTxt.value; oTxt.value = ''; if ( val ) { var oP = document.createElement('p'); val = val.replace(reg, function( $0 ){ alert($0); /*如果reg没有g标识符则 $0:要匹配的字符 $1:匹配子集1 $2:匹配子集2 $3:匹配子集3 ... 从左至右按顺序排列 */ var r = ''; for ( var i=0;i<$0.length;i++ ) { r += '*'; } return r; }); oP.innerHTML = val; oBox.appendChild( oP ); } } </script>
    </body>
</html>

你可能感兴趣的:(JavaScript,replace)