2017-08-31 75 views
1

我有一個自定義的正則表達式做測試時,如果字符串匹配的模式或不工作正常給出的,當我試圖同什麼來代替字符那與模式不匹配,它似乎不起作用。請幫我明白了,什麼是錯我在它正在做的:替換的動態模式以工作代替所有字符除了在動態字符串

這是我的測試代碼工作正常:

function alphaNumCheckOnKeyPress(event, elementId, customPattern) { 

    var asciiCode = event.which ? event.which : event.charCode; 
    customPattern = (customPattern == undefined ? $('#'+elementId).attr('data-custom') : customPattern); 
    var str = String.fromCharCode(asciiCode); 
    var strToVal = new RegExp('^[a-zA-Z0-9' + customPattern + ']+$'); 

    if (strToVal.test(str)) 
     alert("test passed") 
    else 
     alert("test failed"); 

} 

但是當我試圖用同樣的模式來替換字符,那麼它不工作:

$(document).on('paste blur', '.alphaNum', function(){ 
    var that = this; 
    setTimeout(function() { 
     var customPattern = $(that).attr('data-custom') || ""; 
     $(that).val($(that).val().replace(new RegExp('^[A-Za-z0-9' + customPattern + ']+$', 'g'), '')); 
    }, 0); 
}); 

舉例來說,我傳遞自定義模式下劃線(_),這是被允許和不應該從更換跳過。

+1

必須尋找'.replace(新正則表達式( '[^ A-ZA-Z0-9' + customPattern + '] +', 'G'), '')'。然而,'customPattern'需要逃逸,以避免問題的一點,如果有']',''^''\''或'-'內。 –

+0

謝謝@WiktorStribiżew,它像一個魅力。 – TheMohanAhuja

回答

1

'^[a-zA-Z0-9_]+$'圖案,僅由字字符(字母,數字,_)的整個字符串匹配。您似乎想要除去您在正則表達式字符類中指定的所有字符。

因此,您需要將其設置爲否定字符類,並刪除錨點,^(字符串的開頭)和$(字符串的結尾)。

此外,customPattern需要一點逃逸,以避免如果有]^\-裏面,這是可能有特殊意義的JavaScript的字符類內部,被當作文字字符唯一字符問題必須逃脫。

.replace(new RegExp('[^A-Za-z0-9' + customPattern.replace(/[\]^\\-]/g, '\\$&') + ']+', 'g'), '') 
相關問題