js 实现format
JavaScript 实现字符串格式化
在 JavaScript 中实现字符串格式化可以通过多种方式完成,以下是几种常见的方法:
使用模板字符串(ES6)
模板字符串提供了一种简洁的字符串插值方式,支持多行字符串和表达式嵌入:

const name = 'Alice';
const age = 25;
const formatted = `Name: ${name}, Age: ${age}`;
console.log(formatted); // "Name: Alice, Age: 25"
使用 String.prototype.replace()
通过正则表达式匹配占位符并替换:
function format(str, values) {
return str.replace(/{(\w+)}/g, (match, key) => values[key] || match);
}
const result = format('Name: {name}, Age: {age}', { name: 'Bob', age: 30 });
console.log(result); // "Name: Bob, Age: 30"
使用 printf-style 库(如 sprintf-js)
第三方库提供类似 C 语言的格式化功能:

import { sprintf } from 'sprintf-js';
const formatted = sprintf('Name: %s, Age: %d', 'Charlie', 35);
console.log(formatted); // "Name: Charlie, Age: 35"
自定义格式化函数
实现一个支持位置和命名参数的格式化工具:
function format(str, ...args) {
let i = 0;
return str.replace(/%s|%d|%\{(\w+)\}/g, (match, key) => {
if (match === '%s' || match === '%d') return args[i++];
return args[0][key] || match;
});
}
console.log(format('%s is %d years old', 'Dave', 40)); // "Dave is 40 years old"
console.log(format('%{name} is %{age} years old', { name: 'Eve', age: 45 })); // "Eve is 45 years old"
日期/数字格式化
对于特定类型的数据,可使用内置 API:
// 数字格式化
const num = 1234.567;
console.log(num.toFixed(2)); // "1234.57"
// 日期格式化
const date = new Date();
console.log(date.toLocaleDateString('en-US')); // "7/21/2023"
选择方法时应考虑浏览器兼容性、性能需求和使用场景。模板字符串是现代开发的首选方案,而库函数适合需要复杂格式化的场景。






