In JavaScript, there are multiple options for formatting strings:
Template strings (ES6 ): Using template literals ( ), you can embed the values to be formatted directly into the string:
const amount = 10; console.log(`This is ${amount} times easier!`); // "This is 10 times easier!"
Simultaneous replacements: If you need more complex formatting, consider using simultaneous replacements. This involves replacing all format sequences at once using a regular expression:
const text = "Amount: {0}, Date: {1}"; const values = ["0", "2023-02-08"]; console.log(text.replace(/\{(\d+)\}/g, (match, index) => values[index])); // "Amount: 0, Date: 2023-02-08"
The above is the detailed content of What are the JavaScript Equivalents to printf or String.Format?. For more information, please follow other related articles on the PHP Chinese website!