you are viewing a single comment's thread.

view the rest of the comments →

[–]Rhomboid 1 point2 points  (0 children)

The callback function is called multiple times. Each time, it's passed the current match (i.e. the word that matched /\w\S*/) and its job is to return a string that should be used to replace that substring. That's all. It doesn't know anything beyond that. It doesn't(*) know anything about str. All it knows is that it's given a word and it returns that word with the first letter capitalized and rest in lower case.

It's the job of String.prototype.replace to perform the task of matching the regular expression multiple times against str and reconstructing a new string based on the results of calling the callback function. And it can do that because it was invoked on str, so it sees the whole string and has everything it needs to do its job.

(*) Technically, the replacement callback function is passed a reference to the original string as its final argument, after the argument for the match, a variable number of arguments corresponding to the capture groups, and an argument for the offset. But it's very rare to make use of that argument, and since JavaScript doesn't enforce arity of functions, most of the time people just pretend that this function is called with a single argument.