KiRa
KiRa

Reputation: 924

Placing a value in a parameter in javascript function

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));

Code Reference

Upvotes: 2

Views: 85

Answers (2)

Kai Hao
Kai Hao

Reputation: 689

The String.prototype.replace() function takes an optional function parameter here.

It is just because it's the built-in behavior of the function, if you remove the match it will replace match with amount (in your case). It just simply doesn't make sense.

Upvotes: 4

jobcrazy
jobcrazy

Reputation: 1073

Check MDN, you will find that is the first parameter of the callback function of replace.

Upvotes: 1

Related Questions