Thursday, 5 November 2020

Quick Regex to validate Int and Float

 Int :

// regex.test(String) is JS syntax of regex checking a string

Version 1: /^\+?\d+$/.test(str);
^ is start of string pattern
$ is end of string pattern
\+ is escape, plus sign, ? is match 0 or one time
version 2: /^\d+$/.test(str)l
\d means a match a character in [0-9], + means 1 or many times

https://stackoverflow.com/questions/10834796/validate-that-a-string-is-a-positive-integer
Float:
version 1: /^\-?[0-9]+(e[0-9]+)?(\.[0-9]+)?$/.test(str);
\ - is escape minus sign
version 2: /^[0-9]+(e[0-9]+)?(\.[0-9]+)?$/.test(str);
https://stackoverflow.com/questions/52740718/test-if-a-string-is-a-valid-float-in-javascript

No comments:

Post a Comment