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

◇◆丶佛笑我妖孽 提交于 2020-01-14 09:21:11

问题


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


回答1:


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.



来源:https://stackoverflow.com/questions/7662936/using-replace-and-regex-to-capitalize-first-letter-of-each-word-of-a-string-in-j

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!