我正在尝试将字符串中所有单词的第一个字符大写。
Condition 1. there are some excluded words like:
'of', 'the'
which should not
Condition 2. Those excluded world should not be first in string.
这是我的代码:
const movieTitleFormatter = title => {
if(!title) {
return '';
}
let arr = [];
let exludeWords = ['of', 'the']
arr = title.split(' ');
return arr.map(word =>
{
return exludeWords.includes(word) ? [word] : word.charAt(0).toUpperCase() + word.slice(1);
}).join(' ');
}
console.log(movieTitleFormatter('psycho')); //'Psycho';
console.log(movieTitleFormatter('silence of the lambs')); //'Silence of the Lambs';
console.log(movieTitleFormatter('the last emperor')); //'The Last Emperor'; //Here is shows wrong.
console.log(movieTitleFormatter()); //'';
我做了上面的一个,但是找不到除了第一个单词之外的方法。或者任何其他获得结果的最佳方法?
最佳答案
只需添加另一个条件来检查单词的索引:
const movieTitleFormatter = title => {
if(!title) {
return '';
}
let arr = [];
let exludeWords = ['of', 'the']
arr = title.split(' ');
return arr.map((word, i) =>
{
return exludeWords.includes(word) && i!=0 ? [word] : word.charAt(0).toUpperCase() + word.slice(1);
}).join(' ');
}
console.log(movieTitleFormatter('psycho')); //'Psycho';
console.log(movieTitleFormatter('silence of the lambs')); //'Silence of the Lambs';
console.log(movieTitleFormatter('the last emperor')); //'The Last Emperor'; //Here is shows wrong.
console.log(movieTitleFormatter()); //'';
关于javascript - 除了某些单词外,每个单词的第一个单词都要大写,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60393691/