Javascript字符串替换在满足长度而不是instantanoeus之前不会生效

Javascript string replacement not taking effect until length fulfilled instead of instantanoeus

本文关键字:instantanoeus 替换 字符串 满足 Javascript      更新时间:2023-09-26

我有一个输入电话号码的html element。它同时有一个onkeyuponkeydown事件来执行此操作:

document.getElementById("phone").value = document.getElementById("phone").value.replace(/('d{3})('d{3})('d{4})/, "$1-$2-$3");

现在,当我使用它时,它工作得很好,但它只有在用户键入10个数字后才会进行更改我想要的是在用户输入时显示格式的即时更新

我不知道如何修改代码使其正常工作。

您可以使用此正则表达式在旅途中更新值:

document.getElementById("phone").value = document.getElementById("phone").value.replace(/('d{3})('d{0,3})('d{0,4})/, "$1-$2-$3");

它将立即添加短划线,并在键入

时用数字填充空白