简体   繁体   English

删除最后一个无效字符,而不是第一个(JavaScript验证)

[英]remove last invalid character, not first (javascript validation)

I am trying to write a javascript validation method so that, if more than one capital letter is entered, it removes the other capital letters on the fly. 我正在尝试编写一种JavaScript验证方法,以便在输入多个大写字母的同时,即时删除其他大写字母。 However, it is removing the first capital letter, and I want it to remove the last one (which doesn't exist at x=1 ) 但是,它正在删除第一个大写字母,而我希望它删除最后一个大写字母( x=1不存在)

This is my code... 这是我的代码...

for(var x = 1, j = value.length; x < j; x++){
    if(value.charAt(x) != newValue.charAt(x)){
        valid = false;
        $("#text_10").attr({ 
            "value":$("#text_10").attr("value").replace(value.charAt(x), "")
         });
        finalVal = finalVal.replace(value.charAt(x), "");
    }
}

Is there any way to identify that last typed letter, without reversing the string, so that I can remove the capital letter? 有什么方法可以识别最后键入的字母,而无需反转字符串,以便我可以删除大写字母?

反转您的字符串,然后通过“删除第一个大写字母”代码运行该字符串,然后将其重新反转。

You could use String.replace : 您可以使用String.replace

var one = false;
finalValue = value.replace(/([A-Z])/g, function () {
   if (one) return '';
   one = true;
   return arguments[1];
}); 

Reverse your loop index. 反转循环索引。 Start at value.length and work your way back using x-- rather than x++ until you reach 0. You won't need j either at that point. value.length开始, value.length使用x--而不是x++直到达到0。此时您也不需要j

for (var i = value.length; i > 0; i--) {
    ...
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM