3

If I enter something like this: a1.b22.333, I want it to output either:

1.22333 or 122.333

It gets rid of the non digit characters and any periods beyond 1.

My best guesses at this have been:

obj.value = obj.value.replace( /[^0-9\.{1}]+/g ,  '');     
obj.value = obj.value.replace( /[^0-9\.{2,}]+/g ,'');     
obj.value = obj.value.replace( /[^0-9\.(?=.*\.)]+/g ,'');

But these all output 1.22.333

How can I get rid of that extra period?

Thanks for your help.

phpmeh
  • 1,752
  • 2
  • 22
  • 41
  • 4
    And on what criteria do you work out which of the two numbers you want it to produce? – David Thomas Feb 18 '12 at 18:12
  • It doesn't matter what number it produces. I am just trying to produce a valid number. – phpmeh Feb 18 '12 at 18:23
  • 1
    If it doesn't matter what number it produces then (a) huh?, and (b) why not just remove _all_ the dots? – nnnnnn Feb 18 '12 at 18:33
  • 1
    Yes, but your original question stated that (to use your original example) 1.22333 and 122.333 are both valid results from the same input string, so surely then 122333 is equally valid (and easier to get to). If your _real_ requirement is to always keep the first dot then that disagrees with your initial example. – nnnnnn Feb 18 '12 at 18:45

3 Answers3

18

You can do it like this:

obj.value = obj.value.replace(/[^\d\.]/g, "")
  .replace(/\./, "x")
  .replace(/\./g, "")
  .replace(/x/, ".");

This removes all non numeric, non-period characters, then replaces only the first period with "x", then removes all other periods, then changes "xxx" back to the period.

jfriend00
  • 683,504
  • 96
  • 985
  • 979
  • That's a neat solution, using a placeholder and only regular expressions! Adding a trim for pre- and postperiods is easy as well, if that's required in the specs. Upboat! – Björn Feb 18 '12 at 18:33
1

Mix in some string slicing, and it works splendidly */

/* Remove everything but digits and dots */
var s = ".swe4.53dv3d.23v23.we".replace(/[^\d\.]/g, '');

/* Trim the string from dots */
s = s.replace(/^\.+/, '').replace(/\.+$/, '');

/* Fetch first position of dot */
var pos = s.indexOf(".");

/* Slice the string accordingly, and remove dots from last part */
s = s.slice(0, pos + 1) + s.slice(pos + 1, s.length).replace(/\./g, '');

/* s === "4.5332323" */
Björn
  • 29,019
  • 9
  • 65
  • 81
0

If you use a function to determine the replacement string you can search for any non-digits and then keep count of how many dots have occurred so far:

var val = "a1.b22.333",
    i = 0;

val = val.replace(/\D/g, function(m) {
   if (m===".")
      return (++i > 1) "" : ".";
   return "";
});
nnnnnn
  • 147,572
  • 30
  • 200
  • 241