Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/google-apps-script/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 用:使用正则表达式签名分隔4位数字_Javascript_Jquery_Html_Regex - Fatal编程技术网

Javascript 用:使用正则表达式签名分隔4位数字

Javascript 用:使用正则表达式签名分隔4位数字,javascript,jquery,html,regex,Javascript,Jquery,Html,Regex,我正在定制计时器。我想做的是:如果用户输入1234,它将更改为12:34。问题是什么也没发生(我没有得到例外)。以下是我到目前为止的情况: // check time entry (function ($) { String.prototype.Timeset = function(){ return this.replace(/^\d{2}\:\d$/,"$1,"); } $.fn.Time = function(){ return th

我正在定制计时器。我想做的是:如果用户输入
1234
,它将更改为
12:34
。问题是什么也没发生(我没有得到例外)。以下是我到目前为止的情况:

// 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();" />

我怎样才能做到这一点?我的正则表达式可能也是这个问题的根源。请注意,我不想使用任何外部掩码插件,因为我必须在此插件上应用热键。

让我们试试:

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);

哇!!那很酷。这就是我想要的。嘿,有没有限制用户输入超过23:59的表达式?@DKM:有,但这对于评论来说太复杂了;)你能看到这个吗?它有一个奇怪的问题,如果我使用
.keyup()
而不是
change()
我使用的是chrome,我的意思是使用chrome 28浏览器和
keyup()
,光标总是移动到末尾(你能重现吗?@DKM:当你重新赋值时,总是会发生这种情况。你必须记住光标的位置,赋值,然后恢复位置。我告诉过你这很复杂!)