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] ); &NBSP;&NBSP;&NBSP;&NBSP;&Nbsp; } } } } return result;} //two ways to call var template1= "I am {0}, this year {1}"; var template2= "I am {name}, this year {age}"; var result1=template1.format ("Loogn"), var result2=template2.format ({name: "Loogn", age:22}); //Two results are "I'm Loogn, 22 this year."
string.prototype.format = function () { var s = this; for (var i = 0; i < arguments.length; i++) { var reg = new regexp ("\\{" + i + "\ \}", "GM"); s = s.replace (Reg, arguments[i]); } return s;};
Function stringformat () { if ( arguments.length == 0) return null; var str = arguments[0]; for (var i = 1; i < arguments.length; i++) { var re = new regexp (' \\{' + (i - 1) + ' \ \} ', ' GM '); str = Str.replace (Re, arguments[i]); } return str; } StringFormat ("&type={0}&ro={1}&lplan={2}&plan={3}&={4}&id={5}&id={6} ", data1, data2, data3,data4, data5,data6, DATA7);
Believe that the front-end development of friends have suffered this torture: when the HTML is connected by the hateful single quotation marks, double quotes to get dizzy. Like what:
element.innerhtml = ' <a href= ' + URL + ' "onclick=" alert (\ "+ msg + ' \ ');" > ' + text + ' </a> ';
Here is a string format function:
String.Format = function (str) {
var args = arguments, re = new RegExp ("% ([1-" + Args.length + "])", "G");
return String (str). replace (
Re
Function ($, $) {
return args[$2];
}
);
};
The invocation method is simple:
element.innerhtml = String.Format (' <a href= '%1″onclick= ' alert (\ '%2\ '); " >%3</a> ', URL, msg, text);
JavaScript js string. Format () Collection