js 实现format
实现 JavaScript 的 format 功能
在 JavaScript 中,可以通过多种方式实现类似其他语言中的字符串格式化功能。以下是几种常见的方法:
使用模板字符串(ES6)
ES6 引入的模板字符串可以方便地实现字符串插值:
const name = 'John';
const age = 30;
const message = `My name is ${name} and I'm ${age} years old.`;
console.log(message);
自定义 format 函数
可以创建一个类似 Python 的 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}, your age is {1}'.format('John', 30));
使用对象进行格式化
更灵活的格式化方式,使用命名参数:
String.prototype.format = function(params) {
let result = this;
for (const key in params) {
result = result.replace(new RegExp('\\{' + key + '\\}', 'g'), params[key]);
}
return result;
};
console.log('Hello {name}, your age is {age}'.format({name: 'John', age: 30}));
使用 Intl 对象(国际化格式化)
对于数字、日期等特定格式,可以使用 Intl 对象:
const number = 123456.789;
console.log(new Intl.NumberFormat('de-DE').format(number));
// 输出: 123.456,789
const date = new Date();
console.log(new Intl.DateTimeFormat('en-US').format(date));
// 输出: 5/20/2023
使用 sprintf-js 库
对于更复杂的格式化需求,可以使用第三方库如 sprintf-js:
const sprintf = require('sprintf-js').sprintf;
console.log(sprintf('Hello %s, your age is %d', 'John', 30));
每种方法都有其适用场景,模板字符串适合简单插值,自定义 format 方法提供更多灵活性,而库函数则支持更复杂的格式化需求。






