简体   繁体   English

什么传递给了JavaScript replace()函数?

[英]What is Passed to the JavaScript replace() Function?

I've seen str.replace(..., ...) passed a function for its second argument. 我已经看到str.replace(..., ...)为第二个参数传递了一个函数。 What is passed to the function? 什么传递给函数? It goes like this: 它是这样的:

"string_test".replace(/(.*)_(.*)/, function(a, b) { return a + b; } )

How do you get it to pass the matched groups to the function? 如何获得将匹配的组传递给函数的信息? What are a and b in this case if anything? 在这种情况下, ab是什么? I've been getting undefined . 我一直undefined

The first argument is the entirety of a match, and the rest represent the matched groups. 第一个参数是整个匹配项,其余参数代表匹配的组。 Basically it's like the array returned from .match() . 基本上就像从.match()返回的数组。

If the regex has the "g" modifier, then obviously the function is called over and over again. 如果正则表达式具有“ g”修饰符,则显然该函数会被反复调用。

Example: 例:

var s = "hello out there";

s.replace(/(\w*) *out (\w*)/, function(complete, first, second) {
  alert(complete + " - " + first + " - " + second);
  // hello out there - hello - there
});

edit — in the function, if you want the matched groups as an array, you can do: 编辑 -在函数中,如果要将匹配的组作为数组,则可以执行以下操作:

s.replace(/(\w*) *out (\w*)/, function(complete, first, second) {
  var matches = [].slice.call(arguments, 0);
  alert(matches[0] + " - " + matches[1] + " - " + matches[2]);
  // hello out there - hello - there
});

Of course, as I wrote above that's what you get from the .match() method too. 当然,正如我上面所写,这也是从.match()方法获得的。

我真的不想复制MDN文档及其说明: 将函数指定为参数

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM