js实现sprintf
在 JavaScript 中实现类似 sprintf 的功能可以通过多种方式完成,以下是一些常见的方法:
使用模板字符串(ES6+)
ES6 引入了模板字符串,可以方便地进行字符串插值:
const name = 'Alice';
const age = 25;
const message = `Hello, ${name}! You are ${age} years old.`;
console.log(message); // 输出: Hello, Alice! You are 25 years old.
自定义 sprintf 函数
可以通过自定义函数模拟 sprintf 的行为,支持占位符替换:
function sprintf(format, ...args) {
return format.replace(/%([0-9]+)?s/g, (match, index) => {
const argIndex = index ? parseInt(index) - 1 : 0;
return args[argIndex] !== undefined ? args[argIndex] : match;
});
}
const result = sprintf('Name: %1s, Age: %2s', 'Alice', 25);
console.log(result); // 输出: Name: Alice, Age: 25
使用第三方库
一些流行的第三方库(如 sprintf-js)提供了完整的 sprintf 实现:
import { sprintf } from 'sprintf-js';
const formatted = sprintf('Hello, %s! You are %d years old.', 'Alice', 25);
console.log(formatted); // 输出: Hello, Alice! You are 25 years old.
使用 Intl API 进行格式化
对于数字、日期等复杂格式化,可以使用 Intl API:
const number = 1234.567;
const formattedNumber = new Intl.NumberFormat('en-US', {
style: 'currency',
currency: 'USD'
}).format(number);
console.log(formattedNumber); // 输出: $1,234.57
使用正则表达式替换
通过正则表达式动态替换占位符:

function format(str, ...values) {
return str.replace(/{(\d+)}/g, (match, index) => {
return values[index] !== undefined ? values[index] : match;
});
}
const output = format('Name: {0}, Age: {1}', 'Alice', 25);
console.log(output); // 输出: Name: Alice, Age: 25
以上方法可以根据具体需求选择使用,模板字符串和自定义函数适合简单场景,而第三方库或 Intl API 更适合复杂格式化需求。






