我正在开发自定义时间选择器。我想要做的是:如果用户输入1234
,它将更改为12:34
。问题是根本没有发生任何事情(我没有得到异常(exception))。这是我到目前为止所拥有的:
// check time entry
(function ($) {
String.prototype.Timeset = function(){
return this.replace(/^\d{2}\:\d$/,"$1,");
}
$.fn.Time = function(){
return this.each(function(){
$(this).val($(this).val().Timeset());
})
}
})(jQuery);
HTML 标记:
<input id="txtTime" type="text" maxlength="4" onpaste="return false;" onchange="this.value = this.value.Timeset();" />
我怎样才能实现这个目标?我的正则表达式也可能是这个问题的根源。请注意,我不想使用任何外部 mask 插件,因为我必须在此插件上应用热键
。
最佳答案
让我们试试这个:
function formatTime(s) {
return s.replace(/\D/g, "").replace(/^(\d\d)(\d\d).*$/, "$1:$2");
}
(function ($) {
$.fn.timeInput = function() {
return $(this).change(function() {
$(this).val(formatTime($(this).val()))
});
}
})(jQuery);
关于javascript - 用 : sign using regex 分隔 4 位数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17590909/