它的使用方式是: alert(format("{0} love {1}.","I","You"))//I love you format的实现方式主要是用到了String对象的replace方法:
replace:返回根据正则表达式进行文字替换后的字符串的复制。
1.平时常用到的replace 复制代码 代码如下: function ReplaceDemo(){ var r, re; // 声明变量。 var ss = "The man hit the ball with the bat.
"; ss += "while the fielder caught the ball with the glove."; re = /The/g; // 创建正则表达式模式。 r = ss.replace(re, "A"); // 用 "A" 替换 "The"。 return(r); // 返回替换后的字符串。 } ReplaceDemo(); //A man hit the ball with the bat. while the fielder caught the ball with the glove.
2.替换模式中的子表达式 复制代码 代码如下: function ReplaceDemo(){ var r, re; // 声明变量。 var ss = "The rain in Spain falls mainly in the plain."; re = /(S+)(s+)(S+)/g; // 创建正则表达式模式。 r = ss.replace(re, "$3$2$1"); // 交换每一对单词。 return(r); // 返回结果字符串。 } document.write(ReplaceDemo()); //rain The Spain in mainly falls the in plain.