当前位置: 代码迷 >> JavaScript >> javascript String.format%一 %2和String.formatmodel {k}
  详细解决方案

javascript String.format%一 %2和String.formatmodel {k}

热度:619   发布时间:2012-10-23 12:12:22.0
javascript String.format%1 %2和String.formatmodel {k}
String.format = function(str) {
    var args = arguments, re = new RegExp("%([1-" + args.length + "])", "g");
    return String(str).replace(
    re,
    function($1, $2) {
        return args[$2];
    }
    );
};

String.formatmodel = function(str,model){
	for(var k in model){
		var re = new RegExp("{"+k+"}","g");
		str = str.replace(re,model[k]);
	}
	return str;
}

var temp = "使用%1代码,去实现%2";
alert(String.format(temp,"JS","功能1"));   //会提示使用JS代码,去实现功能1
alert(String.format(temp,"PHP","功能2"));  //会提示使用PHP代码,去实现功能2

var temp = "使用{code}代码,去实现{fun}";
alert(String.formatmodel(temp,{code:"JS",fun:"功能1"}));   //会提示使用JS代码,去实现功能1
alert(String.formatmodel(temp,{code:"PHP",fun:"功能2"}));  //会提示使用PHP代码,去实现功能2

var html = [];
if(r.data){
                        for(var k in r.data){
                            var item = r.data[k];
                            var d = new Date(Number(item.sendtime + "000"));
                            item.sendtime = d.getFullYear() + "-" + (d.getMonth() + 1) + "-" + d.getDate() + " " + d.getHours() + ":" + d.getMinutes() + ":" + d.getSeconds();
                            html.push(String.formatmodel('<li>'+
                                        '<div class="head-img"> <a  target="_blank"><img src="{face_s}" alt="" /></a> </div>'+
                                        '<div class="con"><span><a href="" target="_blank">{user_name}</a> {msg_type_text}:<i class="icon cir-news"></i><a href="{jump_url}" target="_blank">{title}</a></span></div>'+
                                        '<div class="con">{msg}</div>'+
                                        '<div class="con"><em>{sendtime}</em></div>'+
                                    '</li>',item));
                        }
                    }
                    box.append(html.join(" "));
  相关解决方案