js实现format
JavaScript 实现字符串格式化
在 JavaScript 中,可以通过多种方式实现类似 format 的字符串格式化功能。以下是几种常见的方法:
使用模板字符串(ES6)
ES6 引入了模板字符串,可以直接在字符串中嵌入变量:

const name = 'Alice';
const age = 25;
const message = `My name is ${name} and I am ${age} years old.`;
console.log(message); // "My name is Alice and I am 25 years old."
使用 String.prototype.replace 方法
通过正则表达式替换占位符:
function format(str, ...args) {
return str.replace(/{(\d+)}/g, (match, index) => {
return typeof args[index] !== 'undefined' ? args[index] : match;
});
}
const result = format('Hello {0}, your balance is {1}', 'Alice', 100);
console.log(result); // "Hello Alice, your balance is 100"
使用对象替换占位符
支持命名占位符:

function format(str, obj) {
return str.replace(/\{([^}]+)\}/g, (match, key) => {
return obj[key] || match;
});
}
const result = format('Hello {name}, your balance is {balance}', {
name: 'Alice',
balance: 100
});
console.log(result); // "Hello Alice, your balance is 100"
使用 sprintf-js 库
如果需要更复杂的格式化功能,可以使用第三方库如 sprintf-js:
const sprintf = require('sprintf-js').sprintf;
const result = sprintf('Hello %s, your balance is %d', 'Alice', 100);
console.log(result); // "Hello Alice, your balance is 100"
自定义格式化函数
结合日期、数字等格式化需求:
function formatDate(date) {
return date.toISOString().split('T')[0];
}
const today = new Date();
const message = `Today is ${formatDate(today)}`;
console.log(message); // "Today is 2023-10-01"
以上方法可以根据具体需求选择使用,模板字符串是最简单的方式,而自定义函数或库可以满足更复杂的需求。






