view raw
Simon Simon - 11 months ago 29
Javascript Question

Remove Any Non-Digit And Check if Formatted as Valid Number

I'm trying to figure out a regex pattern that allows a string but removes anything that is not a digit, a

, or a leading

I am looking for the simplest way of removing any non "number" variables from a string. This solution doesn't have to be regex.

This means that it should turn

1.203.00 -> 1.20300
-1.203.00 -> -1.20300
-1.-1 -> -1.1
.1 -> .1
3.h3 -> 3.3
4h.34 -> 4.34
44 -> 44
4h -> 4

The rule would be that the first period is a decimal point, and every following one should be removed. There should only be one minus sign in the string and it should be at the front.

I was thinking there should be a regex for it, but I just can't wrap my head around it. Most regex solutions I have figured out allow the second decimal point to remain in place.


You can use this replace approach:

  • In the first replace we are removing all non-digit and non-DOT characters. Only exception is first hyphen that we negative using a lookahead.
  • In the second replace with a callback we are removing all the DOT after first DOT.

Code & Demo:

var nums = ['1.203.00', '-1.203.00', '-1.-1', '.1', '3.h3', '4h.34', '4.34', '44', '4h']


for (i=0; i<nums.length; i++)
  document.writeln(nums[i] + " => " + nums[i].replace(/(?!^-)[^\d.]+/g, "").
         function($0, $1, $2) { return $1 + $2.replace(/[.]+/g, ''); })