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.

4
  • 4
    And on what criteria do you work out which of the two numbers you want it to produce? Commented Feb 18, 2012 at 18:12
  • It doesn't matter what number it produces. I am just trying to produce a valid number. Commented Feb 18, 2012 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? Commented Feb 18, 2012 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. Commented Feb 18, 2012 at 18:45

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

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!
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" */

1 Comment

Thank you. I was thinking too narrowly with the regex. Works great.
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 "";
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.