我正在尝试使用
"string".replace(regex, myFunction('$1'));
其中myFunction将匹配的字符串作为参数,并根据包含的内容执行不同的操作并返回不同的字符串。我发现这只是传递'$ 1'字符串而不是它代表的字符串。
有什么建议吗?
答案 0 :(得分:2)
你真的很接近,只需稍微改变var result = "string".replace(regex, myFunction);
所以它需要两个参数;第二个是捕获组的内容。然后这样做:
myFunction
或者,如果您无法更改var result = "string".replace(regex, function(m, c0) {
return myFunction(c0);
});
,请执行以下操作:
replace
请注意,在这两种情况下,我们都将函数引用作为第二个参数传递给replace
,我们不是直接调用函数。当你在第二个参数中给var rex = /test (.*)/;
// Changing myFunction to expect two args:
function myFunction1(m, c0) {
return c0.toUpperCase();
}
console.log("test one".replace(rex, myFunction1));
// Leaving myFunction alone and wrapping the call to it:
function myFunction2(c0) {
return c0.toUpperCase();
}
console.log("test two".replace(rex, function(m, c0) {
return myFunction2(c0);
}));
一个函数时,它会调用它,将完整的正则表达式匹配作为第一个参数传递,然后任何捕获组都匹配为后续参数。
实例:
var objArray = [
{ name: 'APPLE', type: 'FRUIT' },
{ name: 'ONION', type: 'VEGETABLE' }
];
var csvString = objArray
.map(function(item){ return item.name; })
.join();
// ===================
// es6 version of the above
// ===================
// var csvString = objArray.map((item) => item.name).join();
// ===================
console.log(csvString)