Reputation: 799
I need to alter users input and leave in the box only integer or decimal values, i.e. 4567 or 354.5635. I use the following statement:
v = v.replace(/[^\d\.]+/g, "");
But this allows multiple decimal points such as 345.45.345.67. How do I ensure that only one point is there?
Upvotes: 0
Views: 5487
Reputation: 21
v = v.replace(/[A-Za-z$-]/g, "");
// This will replace the alphabets
v = v.replace(/[^\d]*(\d+(\.\d+)?)?.*/g, "$1");
// This will replace other then decimal
Upvotes: 1
Reputation:
Not sure if JS can do lookahead assertions, but if it can it could be done with a regex IF JS can also do reverse(input_string).
A reverse is needed because you want to allow the FIRST dot, and take out the rest.
However, search progresses left to right.
/(?:[.](?=.*[.])|[^\d.])+/g
will take out all but the last '.'
So, the string has to be reversed, substituted, then reversed again.
Perl code example:
my $ss = 'asdf45.980.765';
$ss = reverse $ss;
$ss =~ s/(?:[.](?=.*[.])|[^\d.])+//g;
$ss = reverse $ss;
print $ss;
Output: 45.980765
Upvotes: 2
Reputation: 2710
I'd recommend to use parseFloat
here:
v = parseFloat(v);
This will guarantee you to have integer/decimal value or NaN
.
Upvotes: 0