我正在尝试编写一个函数,该函数将从输入元素获取内容,并尝试将输入框中输入的数字格式化为 MM/YY。以下是我的解决方案,我想减少它的行数。有人可以帮我写一个更好的函数来做到这一点吗?
如果你看到这个,它会自动插入斜杠。工作演示:https://codepen.io/ermauliks/pen/EXBryQ?editors =1010
function formatString(string) {
return string.replace(
/^([1-9]\/|[2-9])$/g, '0$1/' // To handle 3/ > 03/
).replace(
/^(0[1-9]{1}|1[0-2]{1})$/g, '$1/' // 11 > 11/
).replace(
/^([0-1]{1})([3-9]{1})$/g, '0$1/$2' // 13 > 01/3
).replace(
/^(\d)\/(\d\d)$/g, '0$1/$2' // To handle 1/11 > 01/11
).replace(
/^(0?[1-9]{1}|1[0-2]{1})([0-9]{2})$/g, '$1/$2' // 141 > 01/41
).replace(
/^([0]{1,})\/|[0]{1,}$/g, '0' // To handle 0/ > 0 and 00 > 0
).replace(
/[^\d\/]|^[\/]{0,}$/g, '' // To allow only numbers and /
).replace(
/\/\//g, '/' // Prevent entering more than 1 /
);
}
event.target.value = formatString(value);
Run Code Online (Sandbox Code Playgroud)
小智 13
这是一个增强版本,其中用户不输入 / (自动添加)并允许删除(其他解决方案阻止删除斜杠):
function cc_expires_format(string) {
return string.replace(
/[^0-9]/g, '' // To allow only numbers
).replace(
/^([2-9])$/g, '0$1' // To handle 3 > 03
).replace(
/^(1{1})([3-9]{1})$/g, '0$1/$2' // 13 > 01/3
).replace(
/^0{1,}/g, '0' // To handle 00 > 0
).replace(
/^([0-1]{1}[0-9]{1})([0-9]{1,2}).*/g, '$1/$2' // To handle 113 > 11/3
);
}
Run Code Online (Sandbox Code Playgroud)
小智 6
function formatString(e) {
var inputChar = String.fromCharCode(event.keyCode);
var code = event.keyCode;
var allowedKeys = [8];
if (allowedKeys.indexOf(code) !== -1) {
return;
}
event.target.value = event.target.value.replace(
/^([1-9]\/|[2-9])$/g, '0$1/' // 3 > 03/
).replace(
/^(0[1-9]|1[0-2])$/g, '$1/' // 11 > 11/
).replace(
/^1([3-9])$/g, '01/$1' // 13 > 01/3 //UPDATED by NAVNEET
// ).replace(
// /^(0?[1-9]|1[0-2])([0-9]{2})$/g, '$1/$2' // 141 > 01/41
).replace(
/^0\/|0+$/g, '0' // 0/ > 0 and 00 > 0 //UPDATED by NAVNEET
).replace(
/[^\d|^\/]*/g, '' // To allow only digits and `/` //UPDATED by NAVNEET
).replace(
/\/\//g, '/' // Prevent entering more than 1 `/`
);
}
Run Code Online (Sandbox Code Playgroud)