Home >Web Front-end >JS Tutorial >How Can I Achieve printf/String.Format Functionality for Number Formatting in JavaScript?
JavaScript Analogue of printf/String.Format
You seek a JavaScript equivalent to C/PHP printf() or C#/Java String.Format() specifically for number formatting with thousand separators. The Microsoft Ajax library provides String.Format(), but you prefer a lightweight solution.
Current JavaScript
ES6 introduces template strings, offering a concise alternative:
let soMany = 10; console.log(`This is ${soMany} times easier!`); // "This is 10 times easier!"
Older Solutions
Consider the sprintf() library for JavaScript. Alternatively, implement your own simplified format method as follows:
function format(template, ...args) { return template.replace(/{(\d+)}/g, (match, index) => args[index]); }
This approach avoids successive replacements that can lead to errors when replacement strings contain format sequences.
The above is the detailed content of How Can I Achieve printf/String.Format Functionality for Number Formatting in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!