简体   繁体   中英

Remove all characters from string javascript

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

You've specified a string to replace by enclosing the regex in quotes. Remove the quotes to specify a Regex.

timeStr = timeStr.replace(/[^0-9\.]+/g,"");
$('.hourfield').focusout(function() {

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

    timeStr = $(this).val();

I did some minor changes to the replace() rule and just removed the "dots" which was the main purpose

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

So now it works fine, thanks!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM