Javascript Regular Expressions - Replace non-numeric characters

前端 未结 10 945
清歌不尽
清歌不尽 2021-01-30 12:32

This works:

var.replace(/[^0-9]+/g, \'\');  

That simple snippet will replace anything that is not a number with nothing.

But decimals

10条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-30 13:01

    Here are a couple of jQuery input class types I use:

    $("input.intgr").keyup(function (e) { // Filter non-digits from input value.
        if (/\D/g.test($(this).val())) $(this).val($(this).val().replace(/\D/g, ''));
    });
    $("input.nmbr").keyup(function (e) { // Filter non-numeric from input value.
        var tVal=$(this).val();
        if (tVal!="" && isNaN(tVal)){
            tVal=(tVal.substr(0,1).replace(/[^0-9\.\-]/, '')+tVal.substr(1).replace(/[^0-9\.]/, ''));
            var raVal=tVal.split(".")
            if(raVal.length>2)
                tVal=raVal[0]+"."+raVal.slice(1).join("");
            $(this).val(tVal);
        } 
    });
    

    intgr allows only numeric - like other solutions here.

    nmbr allows only positive/negative decimal. Negative must be the first character (you can add "+" to the filter if you need it), strips -3.6.23.333 to -3.623333

    I'm putting nmbr up because I got tired of trying to find the way to keep only 1 decimal and negative in 1st position

提交回复
热议问题