I want to know what a regex would look like for:
Only whole numbers:
/^\d+$/
# explanation
\d match a digit
+ one or more times
Numbers with at most 2 decimal places:
/^\d+(?:\.\d{1,2})?$/
# explanation
\d match a digit...
+ one or more times
( begin group...
?: but do not capture anything
\. match literal dot
\d match a digit...
{1,2} one or two times
) end group
? make the entire group optional
Notes:
^
and $
are start and end of string anchors. Without these, it will look for matches anywhere in the string. So /\d+/
matches '398501'
, but it also matches 'abc123'
. The anchors ensures the entire string matches the given pattern.-?
before the first \d
. Again, ?
denotes "zero or one time."var rx = new RegExp(/^\d+(?:\.\d{1,2})?$/);
console.log(rx.test('abc')); // false
console.log(rx.test('309')); // true
console.log(rx.test('30.9')); // true
console.log(rx.test('30.85')); // true
console.log(rx.test('30.8573')); // false
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With