开发者

remove last invalid character, not first (javascript validation)

I am trying to write a jav开发者_运维知识库ascript validation method so that, if more than one capital letter is entered, it removes the other capital letters on the fly. However, it is removing the first capital letter, and I want it to remove the last one (which doesn't exist at 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?


Reverse your string, then run that through the "remove the first capital letter" code, then re-reverse it back.


You could use 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.

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜