标题大小写一个句子 JavaScript


假设我们要求编写一个函数,该函数接受一个字符串,并修改字符串中每个单词的第一个字母为大写,将其余字母小写。

例如,如果输入字符串是 -

hello world coding is very interesting

输出应为 -

Hello World Coding Is Very Interesting

我们定义一个 capitaliseTitle() 函数,该函数接收一个字符串,并使每个单词的第一个字母大写,并返回该字符串 -

示例

let str = 'hello world coding is very interesting';
const capitaliseTitle = (str) => {
   const string = str
   .toLowerCase()
   .split(" ")
   .map(word => {
      return word[0]
      .toUpperCase() + word.substr(1, word.length);
   })
   .join(" ");
   return string;
}
console.log(capitaliseTitle(str));

输出

控制台输出将为 −

Hello World Coding Is Very Interesting

更新于: 2020-08-18

245 次浏览

开启您的 职业生涯

完成课程并获得认证

开始
广告
© . All rights reserved.