5

The following,though redundant, works perfectly :

'leap of, faith'.replace(/([^ \t]+)/g,"$1");

and prints "leap of, faith", but in the following :

'leap of, faith'.replace(/([^ \t]+)/g,RegExp.$1); it prints "faith faith faith"

As a result when I wish to capitalize each word's first character like:

'leap of, faith'.replace(/([^ \t]+)/g,RegExp.$1.capitalize());

it doesn't work. Neither does,

'leap of, faith'.replace(/([^ \t]+)/g,"$1".capitalize);

because it probably capitalizes "$1" before substituting the group's value.

I want to do this in a single line using prototype's capitalize() method

Daud
  • 7,429
  • 18
  • 68
  • 115

1 Answers1

13

You can pass a function as the second argument of ".replace()":

"string".replace(/([^ \t]+)/g, function(_, word) { return word.capitalize(); });

The arguments to the function are, first, the whole match, and then the matched groups. In this case there's just one group ("word"). The return value of the function is used as the replacement.

Pointy
  • 405,095
  • 59
  • 585
  • 614
  • Thanks. But how does JS know that the two arguments to the function will be the one that you specified ? – Daud Oct 05 '11 at 15:01
  • ?? Uhh ... I don't understand the question. JavaScript "knows" because that's just how the ".replace()" method is specified and implemented. If the second argument is a function, then the runtime system calls it with arguments taken from the result of the regex match. – Pointy Oct 05 '11 at 15:06
  • I mean, I checked at the mozilla reference : https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String/replace and they didn't mention that THESE PARTICULAR results of the regex match will be passed when 2 arguments are specified – Daud Oct 05 '11 at 15:30
  • See where it says, in the **Specifying a function as a parameter** section, that "p1, p2, ..." are the "parenthesized submatch strings"? – Pointy Oct 05 '11 at 15:37
  • But it doesn't say that in the case of multiple arguments, the first argument will be the whole match, and thereafter u would have matched groups. Also, inside the function, if we print _ and word, both are the same. What, the, is the diff between "whole match" and "matched groups" ? – Daud Oct 05 '11 at 15:57
  • Yes, it most certainly does say that. That's what the table means in that section - it's telling you what the arguments are. The "whole match" would be different than the first "matched word" if you had a pattern like `/something (matched word) something/` - the "something" parts would be part of the first argument but the second would only be "matched word". – Pointy Oct 05 '11 at 15:59
  • Thanks. I didn't realize that the arguments were mentioned in the order they were to be specified, not randomly – Daud Oct 05 '11 at 16:22