使用替换和正则表达式在 JavaScript 中将字符串的每个单词的第一个字母大写

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7662936/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 00:51:11  来源:igfitidea点击:

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

javascriptregexcapitalization

提问by Daud

The following,though redundant, works perfectly :

以下虽然是多余的,但效果很好:

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

'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"

'leap of, faith'.replace(/([^ \t]+)/g,RegExp.$1);它打印“信仰信仰信仰”

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

因此,当我希望将每个单词的第一个字符大写时,例如:

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

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

it doesn't work. Neither does,

它不起作用。也不行,

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

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

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

因为它可能在替换组的值之前大写“$1”。

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

我想使用原型的 capitalize() 方法在一行中执行此操作

回答by Pointy

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

你可以传递一个函数作为“.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.

该函数的参数首先是整个匹配,然后是匹配的组。在这种情况下,只有一个组(“单词”)。函数的返回值用作替换。