Write a simple stringformat to use for yourself.
functionstringFormat (format, args) {varFormatdata; if(Arguments.length = = 2 && args &&typeof(args) = = "Object") {Formatdata=args; } Else{formatdata= Array.prototype.slice.call (arguments, 1); } varPattern = []; for(varKeyinchformatdata) {Pattern.push ("\\{" + key + "\ \}"); } if(!pattern.length) {returnformat; } Pattern= Pattern.join ("|"); returnFormat.replace (NewREGEXP (Pattern, "img"), function(Matchvalue, index, inputstring) {varKey = Matchvalue.slice (1,-1); returnFormatdata[key]; });}
Make some changes to make the code shorter
functionStringFormat () {vardata, args =arguments, arr=[], I= 0; Data= (Args.length = = 2 && args[1] &&typeof(args[1]) = = = "Object")? ARGS[1]: Array.prototype.slice.call (args, 1); for(arr[i++]inchdata); returnArr.length? Args[0].replace (NewREGEXP ("\\{" + arr.join ("\\}|\\{") + "\ \}", "IMG"), function(val) {returnData[val.slice (1,-1)]; }): Args[0];}
Compression
function StringFormat () {var e,t=arguments,n=[],r=0;e=t.length==2&&t[1]&& typeof t[1]== "Object"? T[1]:array.prototype.slice.call (t,1); for (n[r++] in E); return n.length?t[0].replace (new RegExp ("\\{" +n.join ("\\}|\\{") + "\ \}", "img"),function (t) {return E[t.slice (1,-1)]}): T[0]}
View Code
Example 1
StringFormat ();//undefinedStringFormat ("1 {0} 3 {1}");//"1 {0} 3 {1}"StringFormat ("1 {0} 3 {1}", 2);//"1 2 3 {1}"StringFormat ("1 {0} 3 {1}", 2, 4);//"1 2 3 4"StringFormat ("1 {0} 3 {1}", [2, 4]);//"1 2 3 4"StringFormat ("1 {0} 3 {1}", [2]);//"1 2 3 {1}"StringFormat ("1 {a} 3 {b}", {a:2, B:4}); //"1 2 3 4"StringFormat ("1 {a} 3 {b}", {a:2}); //"1 2 3 {b}"StringFormat ("1 {a} 3 {b}", {a:2, B:4},1, 2);//"1 {a} 3 {b}"StringFormat ("1 {0} 3 {1}", [2, 4], 4, 5);//"1 2,4 3 4"' # #示例2 '//multi-line notation Plus ' \ 'varMline = "My name is {name},i am {age}. My name is {name},i am {age}. My name is {name},i am {age}."; StringFormat (Mline, {name:' Lranye ', Age:12});/*Result: My name is lranye,i am 12.My name was lranye,i am 12.My name is lranye,i am.*///Execution:StringFormat (mline, {name:' {age} ', Age:12});/*Result: My name is {age},i am 12.My name was {age},i am 12.My name is {age},i AM].*/
Note that in
To denote a slash ' \ ' in a JavaScript string, write ' \ \ ' With the escape character ' \ '
For example, ' \ ' corresponds to write ' \ \ ', ' \ \ ' corresponds to write ' \\\\ '
If you declare and assign a variable str as follows
var str= "1\2\3\4";
In fact, the STR value is "1234"
The correct representation is str= "1\\2\\3\\4"
A simple stringformat.