js 实现format
实现 JavaScript 的 format 功能
JavaScript 原生没有内置的 format 方法,但可以通过多种方式实现类似的功能。以下是几种常见的实现方法:
使用字符串模板
ES6 引入了模板字符串,可以方便地格式化字符串:
const name = 'Alice';
const age = 25;
const message = `Hello, my name is ${name} and I'm ${age} years old.`;
console.log(message);
自定义 format 函数
可以创建一个自定义的 format 函数,类似于其他语言中的字符串格式化:

String.prototype.format = function() {
const args = arguments;
return this.replace(/{(\d+)}/g, function(match, number) {
return typeof args[number] != 'undefined' ? args[number] : match;
});
};
console.log('Hello, {0}! You are {1} years old.'.format('Alice', 25));
使用对象进行命名替换
如果需要更灵活的命名替换,可以使用对象:
String.prototype.format = function(params) {
let formatted = this;
for (const [key, value] of Object.entries(params)) {
formatted = formatted.replace(new RegExp(`\\{${key}\\}`, 'g'), value);
}
return formatted;
};
console.log('Hello, {name}! You are {age} years old.'.format({name: 'Alice', age: 25}));
使用现代 JavaScript 的标签模板
ES6 的标签模板可以提供更强大的格式化功能:

function format(strings, ...values) {
return strings.reduce((result, str, i) => {
return result + str + (values[i] || '');
}, '');
}
const name = 'Alice';
const age = 25;
console.log(format`Hello, ${name}! You are ${age} years old.`);
使用第三方库
如果需要更复杂的格式化功能,可以考虑使用第三方库如:
sprintf-js:实现了 C 风格的格式化string-format:提供了类似 Python 的格式化功能
安装 sprintf-js 示例:
const sprintf = require('sprintf-js').sprintf;
console.log(sprintf('Hello, %s! You are %d years old.', 'Alice', 25));
每种方法都有其适用场景,可以根据具体需求选择最适合的实现方式。






