โœจminus one

JS โŸฉ value โŸฉ primitive โŸฉ String โŸฉ method โŸฉ .replace() โŸฉ example โŸฉ minus one

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

Last updated