Javascript Regular Expressions - Replace non-numeric characters

Solution 1:

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

Solution 2:

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.

Solution 3:

Try this:

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

Solution 4:

Try this:

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

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

Solution 5:

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