js中有时需要格式化一个字符串,但js string类并没有format函数,有时候动态填充的数据太长,拼接起来很麻烦,我们可以通过string类原型扩展自定义一个,方便使用,下面是format的一个简单实现:
1
2
3
4
5
6
7
8
9
|
String.prototype.format=
function
(){
//将arguments转化为数组(ES5中并非严格的数组)
var
args = Array.prototype.slice.call(arguments);
var
count=0;
//通过正则替换%s
return
this
.replace(/%s/g,
function
(s,i){
return
args[count++];
});
}
|
示例:
1
2
3
|
var
s=
"my name is %s, I'm %s years old, and I have %s brother."
s=s.format(
"wendy"
,24,2)
结果s为:
"my name is wendy, I'm 24 years old, and I have 2 brother."
|