Using replace and regex to fill the first letter of each word in a string in JavaScript

The following, although redundant, works fine:

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

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

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

As a result, when I want to use every word of the first character, for example:

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

he does not work. Also,

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

because he probably capitalizes "$ 1" before replacing the group value.

I want to do this on a single line using the prototype capitalize () method

+5
source share
1 answer

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

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

- , -, , . ( "" ). .

+11

All Articles