我有这个字符串:
global_filter[default_fields[0]]
我想将其转换为此字符串:
global_filter[dashboard_fields[0]]
我想使用replace函数来检测匹配的子字符串' default_fields'然后将其替换为' dashboard_fields'。
首先我试试这个:
var str = "global_filter[default_fields[0]]";
var regex = /\w+\[(.+)\[\d+\]\]/;
str.replace(regex, function(match, index){
console.log(match); console.log(index);
});
=> global_filter[default_fields[0]]
=> default_fields
由于某些奇怪的原因,匹配的子字符串作为索引参数,而不是匹配参数。 index参数应该是找到匹配的位置。显然,我做错了什么。所以我尝试使用正向前瞻:
str.replace(/(?=\w+\[).+(?=\[\d+\]\])/, function(match, index){
console.log(match); console.log(index);
})
=> global_filter[default_fields
=> 0
这显然也不起作用。我怎么能让匹配等于我想要的子串呢?
答案 0 :(得分:1)
您无需替换回调函数,只需将捕获的组用作:
var str = "global_filter[default_fields[0]]";
str = str.replace(/(\w+\[).+?(\[\d+\]\])/g, '$1dashboard_fields$2');
//=> global_filter[dashboard_fields[0]]
原因您在打印index
时看到捕获的组的原因是因为index
始终应该是所有匹配组之后的回调函数的最后一个参数。请注意,您已将(.+)
作为已捕获的群组。
所以如果你使用:
str.replace(/\w+\[(.+)\[\d+\]\]/, function(m0, m1, index){
console.log(m0); console.log(index);
});
然后它将正确打印:
global_filter[default_fields[0]]
0