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.
The \d is used to express single number in regex. The number can be any number which is a single number. The \d can be used to match single number. Alternatively the [0-9] can be used to match single number in a regular expression.
The regex [0-9] matches single-digit numbers 0 to 9. [1-9][0-9] matches double-digit numbers 10 to 99. That's the easy part. Matching the three-digit numbers is a little more complicated, since we need to exclude numbers 256 through 999.
For example, the replacement pattern $1 indicates that the matched substring is to be replaced by the first captured group.
In regex, there are basically two types of characters: Regular characters, or literal characters, which means that the character is what it looks like. The letter "a" is simply the letter "a". A comma "," is simply a comma and has no special meaning.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With