2011-09-16 10 views
0

這是一個跟進到另一個崗位,我把這裏的Javascript不匹配正確的單詞進行驗證

所以我有一個表格,我不想接受某些詞。然而,假設你輸入「Post」我不希望它匹配「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; 
        } 
      }); 

回答

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 
} 
0

你需要加倍逃避你反斜槓(\),因爲它是在一個字符串:

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