字符串在js中格式化

70 阅读1分钟

扩展 String 原型

String.prototype.format = String.prototype.f = function(){
	var args = arguments;
	return this.replace(/\{(\d+)\}/g, function(m,n){
		return args[n] ? args[n] : m;
	});
};

函数形式

/**
 * @param {string} format
 * @param {array} args
 */
function format(format, args) {
	return format.replace(/\{(\d+)\}/g, function (m, n) {
		return args[n] !== undefined ? args[n] : m
	})
}

示例用法

var formattedString = "Hello, {0}! You have {1} new messages.".format("Alice", 5);
console.log(formattedString);  // 输出: "Hello, Alice! You have 5 new messages."

var formattedString2 = "Temperature is {0}°C.".f(22);
console.log(formattedString2);  // 输出: "Temperature is 22°C."

在这些示例中,{0}{1} 被替换为传递给 formatf 方法的参数