是否有方法检测和更改输入值格式

Is there any way to detect and change the input value format?

本文关键字:输入 格式 有方法 检测 是否      更新时间:2023-09-26

我正在用正则表达式检查和验证文本区域值我想改变格式,像这样:用户输入:

123456

更改为:

12/34/56

可以在纯js中完成吗?

编辑:

这就是我所做的:

 function changeIt() {
  var inputChanger = document.getElementById("id").value.replace(something , something);
  document.getElementById("id").value = inputChanger;
}

但不知道如何继续

试试这样:

注意:要使这段代码工作,HTML必须在JavaScript之前,但是堆栈溢出显然会重新排序代码片段,以始终优先显示JS (?)

var input = document.getElementById('my-input');
function format() {
  // 'd matches a digit, 
  // parenthesis let you use the matched values as $n in the replacement string
  input.value = input.value.replace(/('d'd)('d'd)('d'd)/, '$1/$2/$3');
}
// you probably only need one of these, but it doesn't hurt to have both
input.addEventListener('change', format);
input.addEventListener('keyup', format);
<input type="text" id="my-input" />

当然,它也可以用一些jQuery和像http://jquery-plugins.net/maskjs-jquery-plugin-to-mask-inputs这样的插件来完成-但我认为即使你最终这样做了,也应该了解幕后发生的事情。