[Javascript] template literal tag

Zhentiw發表於2024-06-16
function currency(strings, ...values) {
    return strings.reduce((result, string, i) => {
        let value = values[i - 1];
        if (typeof value === "number") {
            value = `$${value.toFixed(2)}`;
        }
        return result + value + string;
    });
}

const price = 19.5005;
const formatted = currency`The total price is ${price}.`;

console.log(formatted); // The total price is $19.50.

相關文章