Javascript regex, allow only numbers and commas

Ok, I need help replacing the regex in javascript.

I have this function that accepts everything except numbers .. but I also need to allow commas.

function validDigits(n){
return n.replace(/\D+/g, '');}

I'm still pretty cloudy in the regex syntax, so if anyone could help me, I would really appreciate it.

+5
source share
3 answers
function validDigits(n){
   return n.replace(/[^\d,]+/g, '');
}

When you use square brackets and a ^ after the open bracket, you look for every character that is not one of them between the brackets, so if you use this method and look for anything that is not a number or comma, it should work fine.

+10
source

Use class characters:

/[^\d,]+/g
0
source

This code is wonderful, you choose the regular expression model that you want, if the character is not allowed, it is deleted.

<script type="text/javascript"> 
var r={
'special':/[\W]/g,
'quotes':/['\''&'\"']/g,
'notnumbers':/[^\d]/g,
'notletters':/[A-Za-z]/g,
'numbercomma':/[^\d,]/g,
}

function valid(o,w){
o.value = o.value.replace(r[w],'');
}
</script>

HTML

<input type="text" name="login" onkeyup="valid(this,'numbercomma')" /> 
0
source

All Articles