How might I efficiently use regex to match input that could be a positive or negative dollar amount or percentage.
So it would match input like: 12, -60, $25.50, -$1.5, +$25,000, 5.5%, -100%, +100%, 0.01%
And return false with input like: Text, +$10%, -5.001
I've been evaluating them separately with:
function percentValue(input) {
regex = /^[+-]?\$?(?=.)(\d*|\d{1,3}(,\d{3})*)?(\.\d{1,2})?$/;
return regex.test(input);
}
function dollarValue(input) {
regex = /^[+-]? *100(\.0{0,2})? *%?$|^[+-]? *\d{1,2}(\.\d{1,2})? *%?$/;
return regex.test(input);
}
Results
percentValue('5.5%'); // True
percentValue('-100%'); // True
percentValue('+.01%'); // True
percentValue('0.001'); // False
percentValue('101%'); // False
percentValue('$100%'); // False
dollarValue('+$12'); // True
dollarValue('-$60.5'); // True
dollarValue('$25,000'); // True
dollarValue('-$5.001'); // False
dollarValue('1,00.25'); // False
dollarValue('$text'); // False
I've been unsuccessful trying to combine them into one. Should I be using another lookahead for the percentage?
var test = [ '12', '-60', '$25.50', '-$1.5', '+$25,000', '5.5%', '-100%', '+100%', '0.01%', 'Text', '+$10%', '-5.001', ]; console.log(test.map(function (a) { return a+':'+/^[+-]?(?:\$?\d{1,3}(?:,\d{3})*(?:\.\d\d?)?|(?:100|\d\d?)(?:\.\d\d?)?%)$/.test(a); }));
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.