JavaScript.format

http://www.xggxgg.com/685.html
String.prototype.format = function(args) {
	var result = this;
	if (arguments.length > 0) {    
		if (arguments.length == 1 && typeof (args) == "object") {
			for (var key in args) {
				if(args[key]!=undefined){
					var reg = new RegExp("({" + key + "})", "g");
					result = result.replace(reg, args[key]);
				}
			}
		}
		else {
			for (var i = 0; i < arguments.length; i++) {
				if (arguments[i] != undefined) {
					var reg = new RegExp("({[" + i + "]})", "g");
					result = result.replace(reg, arguments[i]);
				}
			}
		}
	}
	return result;
}
使用方法:

一,字面量版:"为什么{language}没有format".format ( { language : "javascript" } );

二,数组版:"为什么{0}没有format".format ( [ "javascript" ] );
(function($){
			$.extend({
				format : function(source,args){
					var result = source;
					if(typeof(args) == "object"){
						if(args.length==undefined){
							for (var key in args) {
								if(args[key]!=undefined){
									var reg = new RegExp("({" + key + "})", "g");
									result = result.replace(reg, args[key]);
								}
							}
						}else{
							for (var i = 0; i < args.length; i++) {
								if (args[i] != undefined) {
									var reg = new RegExp("({[" + i + "]})", "g");
									result = result.replace(reg, args[i]);
								}
							}
						}
					}
					return result;
				}
			})
		})(jQuery);
使用方法:

一,字面量版:$.format ( "为什么{language}没有format" , { language : "javascript" } );

二,数组版:$.format ( "为什么{0}没有format" ,  [ "javascript" ] );

相关推荐