js格式化字符串其原理为利用正则表达式替换匹配的字符。
代码为转载他人, 方便自己日后查看:
/** 格式化输入字符串**/
//用法: "hello{0}".format('world');返回'hello world'
String.prototype.format= function(){
var args = arguments;
return this.replace(/\{(\d+)\}/g,function(s,i){
return args[i];
});
}
实例:
var str = "hello{0}{1}".format('my','country');