views:

351

answers:

7

This works:

var.replace(/[^0-9]+/g, '');  

That simple snippet will replace anything that is not a number with nothing.

But decimals are real too. So, I'm trying to figure out how to include a period.

I'm sure it's really simple, but my tests aren't working.

+1  A: 

Did you escape the period? var.replace(/[^0-9\.]+/g, '');

JacobM
A: 

var.replace(/[^0-9\.]+/g, '')

Levi Hackwith
A: 

Try this:

var.replace(/[0-9]*\.?[0-9]+/g, '');

That only matches valid decimals (eg "1", "1.0", ".5", but not "1.0.22")

Eric
Actually, this matches B.006, or blah123. He is looking for the negative case.
Jeff B
Ooh... I misread the question. Ouch.
Eric
A: 

If you don't want to catch IP address along with decimals:

var.replace(/[^0-9]+\.?[0-9]*/g, '');

Which will only catch numerals with one or zero periods

DKinzer
This is wrong. This matches non-numbers, followed by a possible period, followed by numbers. The poster wants to replace all NON-numbers with nothing.
Jeff B
Thanks. I misunderstood the question.
DKinzer
Though I think that this says match anything that starts with one or more numbers, followed by 0 or 1 period followed by 0 or more numbers.
DKinzer
+1  A: 

Replacing something that is not a number is a little trickier than replacing something that is a number.

Those suggesting to simply add the dot, are ignoring the fact that . is also used as a period, so:

This is a test. 0.9, 1, 2, 3 will become .0.9123.

The specific regex in your problem will depend a lot on the purpose. If you only have a single number in your string, you could do this:

var.replace(/.*?(([0-9]?\.)?[0-9]+).*/g, "$1")

This finds the first number, and replaces the entire string with the matched number.

Jeff B
A: 

How about doing this:

var numbers = str.gsub(/[0-9]*\.?[0-9]+/, "#{0} ");
Eric
A: 

If go to text box through tab order by key board, not able to get the cursor in that box, ie select of value is also getting replaced.

sudha