Reputation: 2957
I want an input field that only receives whole and decimal point numbers greater than 2.5
const [foreignPackageWeight, setForeignPackageWeight] = useState('')
<input type="text" value={foreignPackageWeight}
onChange={(e) => {
setForeignPackageWeight(e.target.value.replace(/[^0-9.]/g, ''))
}}
/>
But my regex allows for numbers like
.1
, ..2
, 3...4
, 5.....
How do I change my regex to only allow one decimal point?
Upvotes: 1
Views: 2094
Reputation: 16894
A possible solution is a form of lookaround known as a positive lookbehind. Lookarounds allow you to ensure a pattern exists (or doesn't exist) without that pattern becoming part of the results.
/[^0-9.]|(?<=\..*)\./g
Match any of:
[^0-9.]
Anything that is not a digit or a period(?<=\..*)\.
A period so long as another period appeared earlier in the sequenceUpvotes: 3