如何在表单提交时阻止坏词 [英] How to block bad words upon form submit

查看:105
本文介绍了如何在表单提交时阻止坏词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Javascript的新手,所以请耐心等待。这段代码的目的只是在表单提交时阻止textarea中的废话,丑陋和brat。我想要它,以便在用户按下提交后,坏词会出现( * *)。这纯粹是我已经分配的练习课程,所以它不需要任何实际用途。

I'm new to Javascript, so bear with me. The goal of this code is simply to block the words "crap", "ugly", and "brat" inside of the textarea upon form submit. I want it so that, after the user presses submit, the bad words will star out (**). This is purely a practice lesson I've been assigned, so it doesn't need to have any real use.

此代码的问题在于,一旦按下提交,textarea中的所有文本都消失了。因此,没有任何词语可以阻止。

The problem with this code is that, once you press submit, all the text in textarea disappears. Therefore, there aren't any words to block anymore.

这是代码:

<!DOCTYPE html>

<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="utf-8" />
    <title>Bad Words Blocker Test</title>
    <script type="text/javascript" language="javascript">

        var buttonPress = function ()
        {
            var com = getElementById(comments);
            var filterWords = ["crap", "ugly", "brat"];
            // "i" is to ignore case and "g" for global
            var rgx = new RegExp(filterWords.join(""), "gi");
              function WordFilter(str) {
            return str.replace(rgx, "****");
        }               
        }
    </script>
</head>
<body>
    <form name="badwords" method="post" action="">
    <textarea name="comments" id="comments" rows="5" cols="50"></textarea>
    <br />
    <input id="formSub" type="submit" onclick="(buttonPress())" value="Submit!" />
    </form>
</body>
</html>


推荐答案

将操作分解为函数是一种很好的做法。

It's good practice to breakdown actions to functions.

var button = document.getElementById('formSub');

function replaceWords(event) {
    //Prevent form submission to server 
    event.preventDefault();
    var commentContent = document.getElementById('comments');
    var badWords = ["crap", "ugly", "brat", "basterddouch"];
    var censored = censore(commentContent.value, badWords);
    commentContent.value = censored;
}

function censore(string, filters) {
    // "i" is to ignore case and "g" for global "|" for OR match
    var regex = new RegExp(filters.join("|"), "gi");
    return string.replace(regex, function (match) {
        //replace each letter with a star
        var stars = '';
        for (var i = 0; i < match.length; i++) {
            stars += '*';
        }
        return stars;
    });

}

button.addEventListener('click', replaceWords);

这篇关于如何在表单提交时阻止坏词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆