0
$('.hourfield').focusout(function() {

    var h;
    var m;
    var timeStr = "";
    var time = "";
    var newFormat = "";

    timeStr = $(this).val();

    //Here I would like to remove all characters which isn't numbers
    timeStr = timeStr.replace("/[^0-9\.]+/g","");

    if(timeStr > 0) {

        h = timeStr.substr(0,2);
        m = timeStr.substr(2,2);

        newFormat = h+':'+m;

        //Add new values
        $(this).val(newFormat);
    }

});

网站网址

4

2 回答 2

3

您已通过将正则表达式括在引号中来指定要替换的字符串。删除引号以指定正则表达式。

timeStr = timeStr.replace(/[^0-9\.]+/g,"");
于 2013-03-19T14:40:04.423 回答
0
$('.hourfield').focusout(function() {

    var h;
    var m;
    var timeStr = "";
    var CleanTimeStr = "";
    var newFormat = "";

    timeStr = $(this).val();

我对 replace() 规则做了一些小改动,只是删除了主要目的的“点”

    CleanTimeStr = timeStr.replace(/[.]+/g,"");

    if(CleanTimeStr > 0) {

        h = CleanTimeStr.substr(0,2);
        m = CleanTimeStr.substr(2,2);

        newFormat = h+':'+m;

        //Add new values
        $(this).val(newFormat);
    }
});

所以现在它工作正常,谢谢!

于 2013-03-20T07:39:49.450 回答