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);
});
舉例來說,我傳遞自定義模式下劃線(_),這是被允許和不應該從更換跳過。
必須尋找'.replace(新正則表達式( '[^ A-ZA-Z0-9' + customPattern + '] +', 'G'), '')'。然而,'customPattern'需要逃逸,以避免問題的一點,如果有']',''^''\''或'-'內。 –
謝謝@WiktorStribiżew,它像一個魅力。 – TheMohanAhuja