除了试图将所有单词的所有首字母(即通过regex定义\w+
)转换为大写外,下面的函数不会更改字符串的任何其他部分。
这意味着它没有必要转换的话首字母大写,但不正是问题的标题说:“大写的第一个字母每个字在字符串-的JavaScript”
- 不要分割字符串
- 确定每个字由正则表达式
\w+
,它等效于[A-Za-z0-9_]+
String.prototype.toUpperCase()
仅将功能应用于每个单词的第一个字符。
function first_char_to_uppercase(argument) {
return argument.replace(/\w+/g, function(word) {
return word.charAt(0).toUpperCase() + word.slice(1);
});
}
例子:
first_char_to_uppercase("I'm a little tea pot");
first_char_to_uppercase("maRy hAd a lIttLe LaMb");
first_char_to_uppercase(
"ExampleX: CamelCase/UPPERCASE&lowercase,exampleY:N0=apples"
);
first_char_to_uppercase("…n1=orangesFromSPAIN&&n2!='a sub-string inside'");
first_char_to_uppercase("snake_case_example_.Train-case-example…");
first_char_to_uppercase(
"Capitalize First Letter of each word in a String - JavaScript"
);
编辑2019-02-07:如果您想要实际的Titlecase(即仅首字母大写,所有其他小写):
function titlecase_all_words(argument) {
return argument.replace(/\w+/g, function(word) {
return word.charAt(0).toUpperCase() + word.slice(1).toLowerCase();
});
}
显示这两个示例:
test_phrases = [
"I'm a little tea pot",
"maRy hAd a lIttLe LaMb",
"ExampleX: CamelCase/UPPERCASE&lowercase,exampleY:N0=apples",
"…n1=orangesFromSPAIN&&n2!='a sub-string inside'",
"snake_case_example_.Train-case-example…",
"Capitalize First Letter of each word in a String - JavaScript"
];
for (el in test_phrases) {
let phrase = test_phrases[el];
console.log(
phrase,
"<- input phrase\n",
first_char_to_uppercase(phrase),
"<- first_char_to_uppercase\n",
titlecase_all_words(phrase),
"<- titlecase_all_words\n "
);
}