javascript - 除了某些单词外,每个单词的第一个单词都要大写

标签 javascript ecmascript-6

我正在尝试将字符串中所有单词的第一个字符大写。

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/

相关文章:

javascript - 如何在javascript中实现deque数据结构?

javascript - 在 Javascript 的一次迭代中进行映射和排序?

javascript - Content-Security-Policy 阻止 Vue.js

javascript - 引用错误 : React is not defined in svg file

javascript - 根据许可更改按钮状态 react native

javascript - 取消 JavaScript Promise

javascript - 你能转换显示属性吗?如果没有,最好的解决方案是什么?

javascript - 使用 react.js 从嵌套子项中获取表单值

javascript - 检查字符串是否包含数组中存在的任何关键字

ecmascript-6 - 有没有与 ES6 配合良好的代码复杂性计量工具?