我想写一个javascript函数来格式化消息,这是我的代码:
pattern = "{0},{1}";
args = ["hello", "world"];
pattern.replace(/\{(\d+)\}/g, args["$1"*1]); //$1 stands for \d+, multiply 1 to convert it to a number
我希望结果为hello,world
,但它是undefined,undefined
。
那么如何更改它以使其正确?
答案 0 :(得分:3)
像这样:
pattern.replace(/\{(\d+)\}/g, function($0, $1){
return args[$1];
});
答案 1 :(得分:0)
检查此 demo jsFiddle
/\{(\d+)\},\{(\d+)\}/g
pattern = "{0},{1}";
args = ["hello", "world"];
pattern.replace(/\{(\d+)\},\{(\d+)\}/g, args);
//console.log(pattern.replace(/\{(\d+)\},\{(\d+)\}/g, args));
hello,world