Skip to content

Instantly share code, notes, and snippets.

@we684123
Last active November 29, 2023 03:11
Show Gist options
  • Save we684123/7cb7378f27499eab3997e517c03103b3 to your computer and use it in GitHub Desktop.
Save we684123/7cb7378f27499eab3997e517c03103b3 to your computer and use it in GitHub Desktop.
js formatString(ES3)
/**
* 格式化字串或陣列,將其與後續參數結合。
*
* @param {string|array} input - 要格式化的字串或陣列
* @param {...*} values - 用於替換預留位置的字串的值
* @returns {string} 格式化後的字串
* @throws {Error} 如果 input 不是字串或陣列,將拋出錯誤
*
* @example
* // 基本用法
* formatString("Hello, {0}", "World"); // 回傳 "Hello, World"
* formatString("Numbers: {0} and {1}", 1, 2); // 回傳 "Numbers: 1 and 2"
* formatString(["Hello, ", " {0}"], "World"); // 回傳 "Hello, World"
*
* // 當某個替換值未提供時
* formatString("Hello, {0} {1}", "World"); // 回傳 "Hello, World undefined"
*
* // 當某個替換值為空字串時
* formatString("Hello, {0} {1}", "World", ""); // 回傳 "Hello, World "
*
* // 使用變數名稱替換格式化字串
* var first_word = "World!!!";
* formatString("Hello, {first_word}"); // 回傳 "Hello, World!!! "
* formatString("Hello, {first_word} {1}", "eval", "eval2"); // 回傳 "Hello, World!!! eval2"
* formatString("Hello, {first_word} {first_word}{}"); // 回傳 "Hello, World!!! World!!!{}"
*/
function formatString(input) {
// 檢查是否為陣列
var isArray = Object.prototype.toString.call(input) === '[object Array]';
// 型別檢查
if (typeof input !== 'string' && !isArray) {
throw new Error('第一個參數必須是字串或陣列');
}
// 將 input 轉換為字串
var str;
if (isArray) {
str = input.join('');
} else {
str = input;
}
// 從 arguments 物件中獲取其他參數並轉換為字串
var args = [];
for (var i = 1; i < arguments.length; i++) {
args.push(String(arguments[i]));
}
// 用其他參數替換 "{n}",其中 n 是索引
handle_str_1 = str.replace(/\{(\d+)\}/g, function (match, index) {
return args[parseInt(index, 10)];
});
// 用 eval("String({var_name})") 替換 handle_str_1 中的 "{變數名稱}",並回傳
return handle_str_1.replace(/\{(\w+)\}/g, function (match, var_name) {
return eval('String(' + var_name + ')');
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment