假设我们需要编写一个函数,该函数接受一个字符串并对该字符串中每个单词的首字母大写,并将所有其余字母的大小写更改为小写。
例如,如果输入字符串是-
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