Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript regular expression, allow only numbers and commas

Tags:

regex

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.

like image 533
John Avatar asked Aug 22 '11 13:08

John


People also ask

How do you write only numbers in regular expressions?

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.

Can you use regex on numbers?

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.

What is $1 in regex JS?

For example, the replacement pattern $1 indicates that the matched substring is to be replaced by the first captured group.

Is comma special character in regex?

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.


1 Answers

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.

like image 180
mck89 Avatar answered Nov 15 '22 10:11

mck89