JS写法的format方法
2009-09-04 16:41 hailibu 阅读(463) 评论(1) 编辑 收藏 举报 1 <script type="text/javascript">
2 String.format = function(str,arr)
3 {
4 if (arr.constructor == Array) {
5 for (var i = 0; i < arr.length; i++) {
6 var re = new RegExp('\\{' + (i) + '\\}', 'gm');
7 str = str.replace(re, arr[i]);
8 }
9 }else{
10 for(elem in arr) {
11 var re = new RegExp('\\{' + elem + '\\}', 'gm');
12 str = str.replace(re, arr[elem]);
13 }
14 }
15 return str;
16 }
17 String.prototype.format=function()
18 {
19 var str=this;
20 for(var i=0;i<arguments.length;i++){
21 str=str.replace(eval("/\\{"+i+"\\}/g"),arguments[i]);
22 }
23 return str;
24 }
25
26 var output1 = String.format("My name is {0},{1}",["derry","xie"]);
27 document.writeln(output1);
28
29 var output2 = String.format("My name is {id},{name}",{id:28,name:"derry"});
30 document.writeln(output2);
31
32 var output3 = "My name is {0},{1}";
33 document.writeln(output3.format("derry","xie"));
34 </script>
2 String.format = function(str,arr)
3 {
4 if (arr.constructor == Array) {
5 for (var i = 0; i < arr.length; i++) {
6 var re = new RegExp('\\{' + (i) + '\\}', 'gm');
7 str = str.replace(re, arr[i]);
8 }
9 }else{
10 for(elem in arr) {
11 var re = new RegExp('\\{' + elem + '\\}', 'gm');
12 str = str.replace(re, arr[elem]);
13 }
14 }
15 return str;
16 }
17 String.prototype.format=function()
18 {
19 var str=this;
20 for(var i=0;i<arguments.length;i++){
21 str=str.replace(eval("/\\{"+i+"\\}/g"),arguments[i]);
22 }
23 return str;
24 }
25
26 var output1 = String.format("My name is {0},{1}",["derry","xie"]);
27 document.writeln(output1);
28
29 var output2 = String.format("My name is {id},{name}",{id:28,name:"derry"});
30 document.writeln(output2);
31
32 var output3 = "My name is {0},{1}";
33 document.writeln(output3.format("derry","xie"));
34 </script>