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
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
Share Improve this question asked Oct 5, 2011 at 14:29 DaudDaud 7,88718 gold badges78 silver badges124 bronze badges 3-
Why don't you use
.toUpperCase()
method ? – Jean-Charles Commented Oct 5, 2011 at 14:32 - 1 That converts all the characters in a string to upper case, and the OP wants to convert just the first character. – Pointy Commented Oct 5, 2011 at 14:39
-
2
You could use toUpper + your answer with
str.replace(/\b[a-z]/g, function() {return arguments[0].toUpperCase()})
– Alex K. Commented Oct 5, 2011 at 14:44
1 Answer
Reset to default 13You 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.