JS 原生無 String.Format,字串拼接易讀性差:
// 傳統拼接
var msg = "Welcome to learn '" + lang + "', '" + lang + "' is awesome, you will " + action + " it!";
// 模板字串 (ES6) 雖好,但無法復用模板、無法按索引多次引用同一參數
;(function(exports) {
exports.format = function() {
var args = Array.prototype.slice.call(arguments);
var template = args.shift(); // 第一個參數為模板字串
// 核心:reduce 依次替換 {0}, {1}...
return args.reduce(function(currentTemplate, replacement, index) {
return currentTemplate.replace(new RegExp('\\{' + index + '\\}', 'g'), replacement);
}, template);
};
})(window.utils = window.utils || {});
console.log(utils.format(
"Welcome to learn '{0}', '{0}' is awesome, you will {1} it!",
"JavaScript", "love"
));
// 輸出: Welcome to learn 'JavaScript', 'JavaScript' is awesome, you will love it!
Array.reduce 鏈式替換args.reduce(callback, initialValue)
// callback(previousValue, currentValue, index, array)
// previousValue: 上一次返回結果 (初始為 template)
// currentValue: 當前參數值 (args[index])
// index: 當前索引 (0, 1, 2...)
// 每輪將 {index} 替換為 currentValue,結果傳遞給下一輪
流程圖解:
template: "A{0}B{1}{0}"
args: ["X", "Y"]
第1輪 (index=0): replace("{0}", "X") → "AXB{1}X"
第2輪 (index=1): replace("{1}", "Y") → "AXBYX"
返回 "AXBYX"
utils.format = function(template) {
var args = Array.prototype.slice.call(arguments, 1);
// 支援單個對象參數:format("{name}", {name:"A"})
if (args.length === 1 && typeof args[0] === 'object') {
args = args[0];
}
return template.replace(/\{(\w+)\}/g, function(match, key) {
return args.hasOwnProperty(key) ? args[key] : match; // 找不到保留原樣
});
};
// 使用
utils.format("Hello {name}, age {age}", {name: "Tom", age: 18});
utils.format("Hello {0}, age {1}", "Tom", 18); // 兼容索引
| 方案 | 原理 | 性能 | 特點 |
|---|---|---|---|
| reduce + 正則替換 | n 次正則替換 (n=參數數) | 中 | 代碼極簡、支援索引重複引用 |
| 單次正則 + 回調 | 1 次正則掃描,回調查表 | 高 | 需處理對象/陣列統一、不支援重複索引 (需額外邏輯) |
| 模板字串 (ES6) | 引擎原生 | 最高 | 無法復用模板、無法動態構建模板 |
| sprintf-js 等庫 | 完整 printf 語法 | 中 | 功能全、體積大 |
reduce 實現極其優雅,適合輕量級場景(工具函數、日誌格式化)。sprintf-js、format-util)。format 針對「模板復用、動態模板、索引重複引用」補位。