简体   繁体   中英

What is Passed to the JavaScript replace() Function?

I've seen str.replace(..., ...) passed a function for its second argument. 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? I've been getting 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() .

If the regex has the "g" modifier, then obviously the function is called over and over again.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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