[优化]JavaScript 格式化带有占位符字符串

本文介绍了一个用于格式化字符串并替换占位符的函数实现,包括使用示例和优化方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

/**
 * Format a message with placeholder.
 *
 * Examples: 
 * format("X{0}Y{1}Z{2}") : XYZ
 * format("X{0}Y{1}Z{2}", '1') : X1YZ
 * format("X{0}Y{1}Z{2}", '1', '2') : X1Y2Z
 * format("X{0}Y{1}Z{2}", '1', '2', '3') : X1Y2Z3
 * format("X{0}Y{1}Z{2}", '1', '2', '3', '4') : X1Y2Z3
 * ------------------------------------
 * format() : null
 * format("X{0}Y{1}Z{2}", null) : XYZ
 * format(null, '1') : null
 * ------------------------------------
 * format("{0{0}1{1}2{2}}") : {012}
 * format("{0{0}1{1}2{2}}", 'x') : {0x12}
 * format("{0{0}1{1}2{2}}", 'x', 'y') : {0x1y2}
 * format("{0{0}1{1}2{2}}", 'x', 'y', 'z') : {0x1y2z}
 * 
 * @Author http://blog.youkuaiyun.com/xxd851116
 */
function format( message ) {
	if (!message) return null;
	var ss = message.split(/\{\d+?\}/);
	for ( var i = 0; i < ss.length; i++ ) {
		if (!arguments[i + 1]) break;
		ss[i] += arguments[i + 1];
	}
	return ss.join("");
}


测试用例:

document.writeln("format(\"X{0}Y{1}Z{2}\") : "						+ format("X{0}Y{1}Z{2}") + "<br/>");
document.writeln("format(\"X{0}Y{1}Z{2}\", '1') : "					+ format("X{0}Y{1}Z{2}", '1') + "<br/>");
document.writeln("format(\"X{0}Y{1}Z{2}\", '1', '2') : "			+ format("X{0}Y{1}Z{2}", '1', '2') + "<br/>");
document.writeln("format(\"X{0}Y{1}Z{2}\", '1', '2', '3') : "		+ format("X{0}Y{1}Z{2}", '1', '2', '3') + "<br/>");
document.writeln("format(\"X{0}Y{1}Z{2}\", '1', '2', '3', '4') : "	+ format("X{0}Y{1}Z{2}", '1', '2', '3', '4') + "<br/>");

document.writeln("<hr />");

document.writeln("format() : "										+ format() + "<br/>");
document.writeln("format(\"X{0}Y{1}Z{2}\", null) : "				+ format("X{0}Y{1}Z{2}", null) + "<br/>");
document.writeln("format(null, '1') : "								+ format(null, '1') + "<br/>");

document.writeln("<hr />");
document.writeln("format(\"{0{0}1{1}2{2}}\") : "					+ format("{0{0}1{1}2{2}}") + "<br/>");
document.writeln("format(\"{0{0}1{1}2{2}}\", 'x') : "				+ format("{0{0}1{1}2{2}}", 'x') + "<br/>");
document.writeln("format(\"{0{0}1{1}2{2}}\", 'x', 'y') : "			+ format("{0{0}1{1}2{2}}", 'x', 'y') + "<br/>");
document.writeln("format(\"{0{0}1{1}2{2}}\", 'x', 'y', 'z') : "		+ format("{0{0}1{1}2{2}}", 'x', 'y', 'z') + "<br/>");

上面代码存在参数顺序的bug,感谢KimSoft提出的优化方案:http://blog.youkuaiyun.com/kimsoft/article/details/7860106

String.prototype.format = function(){  
    var args = arguments;  
    return this.replace(/\{(\d+)\}/g,                  
        function(m,i){  
            return args[i];  
        });  
}  
  
var a = "I Love {0}, and You Love {1},Where are {0}! {4}";  
alert(a.format("You","Me"));  



转载于:https://www.cnblogs.com/xingxiudong/archive/2012/08/03/3986910.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值