2
$('#target').val($('#target').val().replace(/[^\d]/g, ""));

I use the above code to leave only numeric characters in an input value I would also like to allow '+' and '-'.

How would I modify the regex to allow this?

Help much appreciated

2 Answers 2

1

Put - and + in the character class.

$('#target').val($('#target').val().replace(/[^-+\d]/g, ""));
Sign up to request clarification or add additional context in comments.

1 Comment

thank you to late in the evening for my brain to work properly here
0

FWIW I use a couple of input classes that I control with jQuery:

<input class="intgr">
<input class="nmbr">

 $("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 strips all non-numeric

nmbr accepts +, -, . and 0-9. The rest of the string gets stripped of all but 0-9 and the first . If you are OK with the + and - being anywhere, Bamar's solution is perfect, short and sweet. I needed the +/- to be only in the first character position if at all, and only one . (i.e. strip out beyond the first period so 2.5.9 would be 2.59)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.