Currently, I use this code to total parenthetical values in a string...
if ((string.match(/\((\d+)\)/g)||[]).length > 0) {
var total = 0;
string.replace(/\((\d+)\)/g, function(outerValue, innerValue){
if (!isNaN(innerValue.toString().trim())) {
total = total + Number(innerValue.toString().trim());
}
});
value = total;
}
...so the string...
(2) dark chocolate, (2) milk chocolate, and (1) white chocolate
...totals 5.
Not willing to leave well-enough alone, I thought it would be cool if I could be a bit fancier and interpret different types of operations, so that someone could write.
(2) dark + (2) milk - (1) white
-or-
(2) dark and (2) milk minus (1) white
So I changed my code to...
if ((string.match(/\((\d+)\)/g)||[]).length > 0) {
var total = 0;
string.replace(/^\((\d+)\)|and\s\((\d+)\)|plus\s\((\d+)\)|\+\s\((\d+)\)/g, function(outerValue, innerValue){
if (!isNaN(innerValue.toString().trim())) {
total = total + Number(innerValue.toString().trim());
}
});
value = total;
}
...but the innerValue returns as undefined. I am able to extract the values when I test with the validator in regex101.com, but not in Javascript.
What am I doing incorrectly?
p.s. Obviously, my code is not complete (in addition to being wrong). Ultimately, I would list all of the operator possibilities (e.g., "+", "plus", "and", "less", "minus", "-", etc.) and would examine the string in outerValue to determine the operator. And, of course, I need to write the logic for commas within a sentence (e.g., allow a single operator in the sentence and apply the operation to each item).