Javascript Regular Expressions - Replace non-numeric characters

前端 未结 10 940
清歌不尽
清歌不尽 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 12:55

    This one just worked for -ve to +ve numbers

    <input type="text" oninput="this.value = this.value.replace(/[^0-9\-]+/g, '').replace(/(\..*)\./g, '$1');">

    0 讨论(0)
  • 2021-01-30 12:56

    Sweet and short inline replacing of non-numerical characters in the ASP.Net Textbox:

     <asp:TextBox ID="txtJobNo" runat="server" class="TextBoxStyle" onkeyup="this.value=this.value.replace(/[^0-9]/g,'')" />
    

    Alter the regex part as you'ld like. Lots and lots of people complain about the cursor going straight to the end when using the arrow keys, but people tend to deal with this without noticing it for instance, arrow... arrow... arrow... okay then... backspace back space, enter the new chars.

    0 讨论(0)
  • 2021-01-30 12:57

    there's a lot of correct answers already, just pointing out that you might need to account for negative signs too.. "\-" add that to any existing answer to allow for negative numbers.

    0 讨论(0)
  • 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

    0 讨论(0)
  • 2021-01-30 13:08

    Try this:

    var.replace(/[^0-9\\.]+/g, '');
    
    0 讨论(0)
  • 2021-01-30 13:08

    Try this:

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

    That only matches valid decimals (eg "1", "1.0", ".5", but not "1.0.22")

    0 讨论(0)
提交回复
热议问题