用regexp替换javascript?
我想写一个javascript函数来格式化消息,这是我的代码:用regexp替换javascript?,javascript,regex,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,但它是未定义的,未定义的。 那么如何更改它以使其正确?如下所示: pattern.replac
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
,但它是未定义的,未定义的
。
那么如何更改它以使其正确?如下所示:
pattern.replace(/\{(\d+)\}/g, function($0, $1){
return args[$1];
});
检查这个
正则表达式模式
JavaScript
控制台结果
“$1”*1
返回NaN
。$0、$1代表什么?@hiway$0只是匹配的字符串,$1是第一个匹配参数。请参阅MDN文档中的replace:但这是硬编码为两个变量的@CD的答案处理了无限多的参数
/\{(\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