Dhaval Marthak Dhaval Marthak - 1 month ago 11
Javascript Question

Separate 4 digits with : sign using regex

I am working on custom timepicker. What I want to do is: If user enters

1234
it will be change to
12:34
. Problem is nothing happens at all (I am not getting exception). Here is what I have so far:

// 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 Markup:

<input id="txtTime" type="text" maxlength="4" onpaste="return false;" onchange="this.value = this.value.Timeset();" />


How can I achieve this? My regular expression may also be the root of this. Note that I don't want to use any external mask plugins as I have to apply
hot-keys
on this one.

Answer

Let's try this:

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

http://jsfiddle.net/LAbFQ/

Comments