I have written a regex to validate a number containing three digits and one decimal but it always return false in all cases.
re = new RegExp("^\d{1,3}\.*\d{0,1}$");
re.test(33.0);
I tried many combinations but its not working. Aim is to validate a number at max 3 digit with one decimal and less than 100. I can handle the less than 100 part.
This one does what you want:
var test = [ 123, 12.34, 100.1, 100, 12, 1.2, 1 ]; console.log(test.map(function (a) { return a+' :'+/^(?:100(?:\\.0)?|\\d{1,2}(?:\\.\\d)?)$/.test(a); }));
Better use regex literal:
var re = /^\d{1,2}(\.\d)?$/;
re.test(33.0);
When passing in numbers beware of floating point precision problems:
re.test(0.1 * 302); // false, because 0.1 * 302 results in 30.200000000000003 :-(
Remember to escape the \\ you regex sequence :
re = new RegExp("^\\\\d{1,3}\\.*\\\\d{0,1}$");
re.test(33.0);
Instead of using Regex Expression Object try using direct javascript
/\d{1,3}\.*\d{0,1}$/.test(33.0)
console.log(/\\d{1,3}\\.*\\d{0,1}$/.test(33.0))
If you want to use RegExp
then try
new RegExp(/\d{1,3}\.*\d{0,1}$/,'i');
re.test(33.0);
let re = new RegExp(/\\d{1,3}\\.*\\d{0,1}$/,'i'); console.log(re.test(33.0));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.