当在中间JavaScript /jQuery中插入字符时,自定义掩码函数不起作用

当在中间JavaScript /jQuery中插入字符时,自定义掩码函数不起作用,javascript,jquery,regex,Javascript,Jquery,Regex,我有一个功能: function maskInput(input, location, delimiter, length) { //Get the delimiter positons var locs = location.split(','); //Iterate until all the delimiters are placed in the textbox for (var delimCount = 0; delimCount <= locs

我有一个功能:

function maskInput(input, location, delimiter, length) {
    //Get the delimiter positons
    var locs = location.split(',');

    //Iterate until all the delimiters are placed in the textbox
    for (var delimCount = 0; delimCount <= locs.length; delimCount++) {
        for (var inputCharCount = 0; inputCharCount <= input.length; inputCharCount++) {

            //Check for the actual position of the delimiter
            if (inputCharCount == locs[delimCount]) {

                //Confirm that the delimiter is not already present in that position
                if (input.substring(inputCharCount, inputCharCount + 1) != delimiter) {
                    input = input.substring(0, inputCharCount) + delimiter + input.substring(inputCharCount, input.length);
                }
            }
        }
    }

    input = input.length > length ? input.substring(0, length) : input;

    return input;
}
这非常有效,但当我尝试从字符串中间删除一个数字,然后再次添加它时,它会将其附加到字符串的末尾,而不会固定到当前位置

例如:

 Entered String: '1234567890'
 After Mask Function Is Called: '123-456-7890'
 Number 5 removed and entered Number 8 instead of 5: '123-467-8908'
请注意,它在字符串末尾追加了数字8


非常感谢您的帮助,谢谢

您应该使用
keyup
而不是
keypress
,因为在
keypress
上,输入的值尚未更改,并且在将新值发布到输入之前应用过滤器。这就是添加新字符的原因

$(document).on('keyup paste drop blur', '#my_phone_number', function() {
    ...
});

此处的工作代码示例

您应该使用
keyup
而不是
keypress
,因为在
keypress
上,输入值尚未更改,并且在将新值发布到输入之前应用过滤器。这就是添加新字符的原因

$(document).on('keyup paste drop blur', '#my_phone_number', function() {
    ...
});
这里的工作代码示例