gpt4 book ai didi

javascript - 使用javascript自动格式化输入日期

转载 作者:行者123 更新时间:2023-11-30 16:24:06 25 4
gpt4 key购买 nike

我有一些 javascript 可以将用户输入的内容自动格式化为 SSN (ddd-dd-dddd)我在转换此脚本以支持日期格式 (mm/dd/yyyy) 时遇到问题

    var val = this.value.replace(/\D/g, '');
var newVal = '';
if (val.length > 4) {
this.value = val;
}
if ((val.length > 3) && (val.length < 6)) {
newVal += val.substr(0, 3) + '-';
val = val.substr(3);
}
if (val.length > 5) {
newVal += val.substr(0, 3) + '-';
newVal += val.substr(3, 2) + '-';
val = val.substr(5);
}
newVal += val;
this.value = newVal;

谁能解释这是如何工作的,并告诉我如何将其转换为我的日期格式?

最佳答案

您发布的代码从 this.value 中删除所有非数字字符,然后根据字符串的长度在正确的位置添加一个“-”。

这是我尝试的一个更容易理解的日期版本:

function insertString(originalString, newString, index) {
return originalString.substr(0, index) + newString + originalString.substr(index);
}

function formatDate(dateString) {
var cleanString = dateString.replace(/\D/g, ''), // Removes all non-numeric characters
output = cleanString.substr(0, 8), // Limit to 8 digits
size = dateString.length;

if (size > 4)
output = insertString(output, '/', 4);

if (size > 2)
output = insertString(output, '/', 2);

return output;
}

然后在你的处理程序中你只需要这样做:

this.value = formatDate(this.value);

关于javascript - 使用javascript自动格式化输入日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34359808/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com