Reputation: 1205
I am creating an input box with an onChange function that will check to see if the characters are only digits and only allow up to one period/dot '.'
The function I have here is not working:
function addPercentSeparator(n) {
let str = n;
let match = str.match(/\d*\.\d*/)
if (match) {
return str;
}
}
I also tried: let match = str.match(/^([0-9]+(\.[0-9]+)?)/)
What I am trying to achieve is only allowing for one period. If the user enters a number without a period, it will append a period to end of string when they click outside the input box.
Upvotes: 0
Views: 419
Reputation: 5148
This regex is supposed to do the trick:
^\d*\.?\d*$
But if you'll ask me, I would make sure there are digits before the dot, using ^\d+\.?\d*$
.
Explanation:
?
, which symbolizes "0 or 1 occurrences".^
and the $
to make sure no parts of the string will be matched if the whole string is illegal.I hope this works for you!
Upvotes: 1