// amount-unit pattern
const amountUnitPattern = /\b(\d+) (\w+)\b/g;
// groups: โฐโ1โโฏ โฐโ2โโฏ
const stock = "1 lemon, 2 cabbages, and 101 eggs";
// matches: โฐโโโโโโฏ โฐโโโโโโโโโฏ โฐโโโโโโโฏ
// minus 1: โ no lemon, 1 cabbage, and 100 eggs
// replacer function: โญโG1โโฎ โญG2โฎ
const minus1 = stock.replace(amountUnitPattern, (match, amount, unit) => {
amount = +amount - 1;
// only one left, remove the 's'
if (amount === 1) unit = unit.slice(0, unit.length - 1);
if (amount === 0) amount = "no";
return amount + " " + unit;
});
ๅ ็บ str.replace() ๆๅฐๆฏๅ match ้ฒ่กๆๅฎ็ replacer function ๆไฝ๏ผๆไปฅๅฆๆๆๅๅชๆฏ่ฆๅฐๆฏๅ match ๅๆไบๅไฝ๏ผไฝไธๅจไนไปฃๆๅพ็ๆๅญ๏ผๅณๅฏไฝฟ็จๆญคๆนๆณใๆๅๅฏไปฅๆ้็จฎๅๆณ็ถไฝๆฏ๏ผstr.match().forEach() ็ๆทๅพ๏ผไฝๅๆฒๆ str.match().forEach() ็็ผบ้ป๏ผๅ ็บๆฒๆ match ๆ๏ผstr.replace() ้ ๅคๅฐฑๆฏไธ้ฒ่กๆฟๆ่ๅทฒ๏ผไธฆไธๆ็ข็้ฏ่ชค่จๆฏใ