js string format
1 <script type="text/javascript">
2
3 //V1 method
4 String.prototype.format = function()
5 {
6 var args = arguments;
7 return this.replace(/\{(\d+)\}/g,
8 function(m,i){
9 return args[i];
10 });
11 }
12
13 //V2 static
14 String.format = function() {
15 if( arguments.length == 0 )
16 return null;
17
18 var str = arguments[0];
19 for(var i=1;i<arguments.length;i++) {
20 var re = new RegExp('\\{' + (i-1) + '\\}','gm');
21 str = str.replace(re, arguments[i]);
22 }
23 return str;
24 }
25
26 var a = "I Love {0}, and You Love {1},Where are {0}! {4}";
27 alert(String.format(a, "You","Me"));
28
29 alert(a.format("You","Me"));
30 </script>
31
32
2
3 //V1 method
4 String.prototype.format = function()
5 {
6 var args = arguments;
7 return this.replace(/\{(\d+)\}/g,
8 function(m,i){
9 return args[i];
10 });
11 }
12
13 //V2 static
14 String.format = function() {
15 if( arguments.length == 0 )
16 return null;
17
18 var str = arguments[0];
19 for(var i=1;i<arguments.length;i++) {
20 var re = new RegExp('\\{' + (i-1) + '\\}','gm');
21 str = str.replace(re, arguments[i]);
22 }
23 return str;
24 }
25
26 var a = "I Love {0}, and You Love {1},Where are {0}! {4}";
27 alert(String.format(a, "You","Me"));
28
29 alert(a.format("You","Me"));
30 </script>
31
32