Javascript Not Matching正确的单词进行验证

时间:2011-09-16 19:39:35

标签: jquery regex

这是我放在这里的另一篇文章的后续跟踪

所以我有一张表格,我不想接受某些单词。然而,如果你输入“发布”我不希望它匹配“pos”所以我已完成该部分脚本不再匹配部分只是整个单词但由于某种原因,如果我输入“肯定”它不匹配“积极”与正则表达式上的单词边界

 var resword = new Array("positive","pos","negative","neg","neutral", "neu","twitter","itunes","facebook","android","forums","RSS Feeds");

 var valueLen = $("#aname").val().length;
 var fail=false;

 var filterElem = $('#aname');
 var filterName = $('#aname').val();

            $.each(resword,function(){
                    if ( filterName.toLowerCase().match("\b"+this+"\b")) {
                            filterElem.css('border','2px solid red');
                            window.alert("You can not include '" + this + "' in your Filter Name");
                            fail = true;
                    }
            });

2 个答案:

答案 0 :(得分:0)

你需要双重转义反斜杠(\),因为它在一个字符串中:

.match("\\b"+this+"\\b")

答案 1 :(得分:0)

我建议采用一种更清晰的方式来实现它,它将所有单词都放在一个正则表达式中。此方法还具有一项功能增强功能,可以只显示一个显示所有非法字词的警报。以下是您可以在此jsFiddle中使用的代码。

function check() {
    var resword = new Array("positive","pos","negative","neg","neutral", "neu","twitter","itunes","facebook","android","forums","RSS Feeds");

    // build one regex with all the words in it
    // assumes that the words themselves dont' have regex characgers in them
    var regex = new RegExp("\\b" + resword.join("\\b|\\b") + "\\b", "ig");
    var filterElem = $('#aname');
    var match, plural, errors = [];

    // call regex.exec until no more matches
    while ((match = regex.exec(filterElem.val())) != null) {
        errors.push(match[0]);   // accumulate each illegal word match
    }
    // if there were any errors, put them together and prompt the user
    if (errors.length > 0) {
        plural = errors.length > 1 ? "s" : "";
        filterElem.css('border','2px solid red');
        alert("You can not include the word" + plural + " '" + errors.join("' and '") + "' in your Filter Name");
    }
    return(errors.length == 0);   // return true if no errors, false if errors
}