Reputation: 487
Okay, I'm needing some help with a regular expression replace in javascript.
I have this function which takes everying out but numbers.. but I need to allow commas as well.
function validDigits(n){
return n.replace(/\D+/g, '');}
I'm still pretty cloudy on regex syntax, so if anyone could help me out I would greatly appreciate it.
Upvotes: 9
Views: 20621
Reputation: 394
This code is great, you choose the regex model you want, if the character is not allowed, it's 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')" />
Upvotes: 0
Reputation: 19231
function validDigits(n){
return n.replace(/[^\d,]+/g, '');
}
When you use square brackets and a ^ after the open bracket you search for every character that is not one of those between brackets, so if you use this method and search for everything that is not a number or a comma it should work well.
Upvotes: 17