js实现format
format 方法实现
在 JavaScript 中实现类似字符串格式化功能可以通过多种方式完成。以下是常见的几种实现方法:
模板字符串 使用 ES6 的模板字符串可以直接插入变量:
const name = 'Alice';
const age = 25;
const formatted = `Name: ${name}, Age: ${age}`;
自定义 format 函数 创建一个接受参数并进行替换的函数:
String.prototype.format = function() {
const args = arguments;
return this.replace(/{(\d+)}/g, function(match, number) {
return typeof args[number] != 'undefined' ? args[number] : match;
});
};
// 使用示例
const str = "Hello {0}, your balance is {1}".format("Alice", 100);
命名参数格式化 实现支持命名参数的格式化:
String.prototype.format = function(params) {
return this.replace(/\{(\w+)\}/g, (_, key) => params[key] || '');
};
// 使用示例
const str = "Hello {name}, your balance is {amount}".format({
name: "Alice",
amount: 100
});
使用正则表达式替换 更灵活的正则表达式替换方案:
function format(str, ...args) {
return str.replace(/{(\d+)}/g, (match, index) =>
args[index] !== undefined ? args[index] : match
);
}
// 使用示例
const result = format("The {0} is {1}", "price", 100);
国际化支持 对于需要本地化的场景:
const messages = {
welcome: "Hello {name}, welcome to {app}",
balance: "Your balance is {amount} {currency}"
};
function localize(key, params) {
let str = messages[key];
for (const [k, v] of Object.entries(params)) {
str = str.replace(new RegExp(`{${k}}`, 'g'), v);
}
return str;
}
// 使用示例
const welcomeMsg = localize('welcome', {name: 'Alice', app: 'MyApp'});
性能考虑
对于高频调用的格式化需求,可考虑以下优化:
- 预编译模板
- 缓存正则表达式
- 使用字符串拼接代替复杂替换
兼容性处理
如果需要支持旧版浏览器:

if (!String.prototype.format) {
String.prototype.format = function() {
// 实现代码
};
}
以上方法提供了不同场景下的字符串格式化解决方案,可根据具体需求选择合适的方式。模板字符串是现代 JavaScript 中最简洁的方案,而自定义 format 方法则提供了更多灵活性。






