繁体   English   中英

Function 将字符串中每个单词的第一个字母大写

[英]Function to capitalize the first letter of each word in a string

我不知道我处理这个问题的方式是否正确:

function capitalizer (string) {
    stringArray = string.split(' ');
    for (let i = 0; i< stringArray.length; i++) { 
        var firstLetter = stringArray[i].charAt(0);
        var firstLetterCap = firstLetter.toUpperCase();
    } 
    return stringArray.join(' ');
} 
console.log(capitalizer('cat on the mat'));

它只是返回原始字符串而不用大写任何东西。

你最好使用.map function

function capitalizer (str) {
  return str
    .split(' ')
    .map((word) => word[0].toUpperCase() + word.slice(1))
    .join(' ')
}

正如 Patrick Roberts 提到的,如果字符串有多个连续空格,此代码将抛出异常。

使用正则表达式提取单词并将 function 应用于每个单词

function capitalize(str) {
    return str.replace(/\w\S*/g, (txt) => txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase());
};

如果您想使用原始代码,您必须确保使用了 firstLetterCap 并将其替换为每个首字母。

function capitalizer (string) {
stringArray = string.split(' ');
for (let i = 0; i< stringArray.length; i++) { 
    var firstLetter = stringArray[i].charAt(0);
    var firstLetterCap = firstLetter.toUpperCase();
    stringArray[i] = firstLetterCap + stringArray[i].slice(1);//cap + everything else
} 
return stringArray.join(' ');
} 
console.log(capitalizer('cat on the mat'));

您也可以使用正则表达式:

  • 将任何前面有空格或行首的小写字母大写......基本上是一个正面的回顾。

 function capitalizer (string) { return string.replace(/(?<=^|\s)[az]/g, s => s.toUpperCase()) } console.log(capitalizer('cat on the mat'));

你可以做:

 const capitalizer = s => s.replace(/\b[az]/g, c => c.toUpperCase()) console.log(capitalizer('cat on the mat'))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM