从字符串javascript中删除所有字符

时间:2013-03-19 14:36:18

标签: javascript jquery

$('.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);
    }

});

URL to website

2 个答案:

答案 0 :(得分:3)

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

timeStr = timeStr.replace(/[^0-9\.]+/g,"");

答案 1 :(得分: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);
    }
});

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