用regexp替换javascript?

时间:2014-04-02 07:03:26

标签: javascript regex

我想写一个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。 那么如何更改它以使其正确?

2 个答案:

答案 0 :(得分:3)

像这样:

pattern.replace(/\{(\d+)\}/g, function($0, $1){ 
   return args[$1];
});

答案 1 :(得分:0)

检查此 demo jsFiddle

Regexp Patten

/\{(\d+)\},\{(\d+)\}/g

的JavaScript

 pattern = "{0},{1}";
 args = ["hello", "world"];

 pattern.replace(/\{(\d+)\},\{(\d+)\}/g, args);
 //console.log(pattern.replace(/\{(\d+)\},\{(\d+)\}/g, args));

控制台结果

hello,world