Reputation: 924
I can't seem to figure it out what is the purpose of match
in this function?. I try to remove it and the result is
NaN 1, NaN 2, and NaN 101
var stock = "1 lemon, 2 cabbages, and 101 eggs";
function minusOne(amount, unit) {
amount = Number(amount) - 1;
if (amount == 1) // only one left, remove the 's'
unit = unit.slice(0, unit.length - 1);
else if (amount == 0)
amount = "no";
return amount + " " + unit;
}
console.log(stock.replace(/(\d+) (\w+)/g, minusOne));
Output of the givin code below
no lemon, 1 cabbage, and 100 eggs
var stock = "1 lemon, 2 cabbages, and 101 eggs";
function minusOne(match, amount, unit) {
amount = Number(amount) - 1;
if (amount == 1) // only one left, remove the 's'
unit = unit.slice(0, unit.length - 1);
else if (amount == 0)
amount = "no";
return amount + " " + unit;
}
console.log(stock.replace(/(\d+) (\w+)/g, minusOne));
Upvotes: 2
Views: 85