Javascript字符串替换函数匹配组

Javascript string replace function on matched group

本文关键字:函数 字符串 替换 Javascript      更新时间:2023-09-26

我想使用

"string".replace(regex, myFunction('$1'));

其中myFunction将匹配的字符串作为参数,根据它包含的内容做不同的事情并返回不同的字符串。我发现这只是传递'$1'字符串,而不是它所代表的内容。

有什么建议吗?

你真的很接近了,只要稍微改变myFunction,让它期望两个参数;第二个将是捕获组的内容。然后这样做:

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);
}));