如何排除字符串中的“ by”等某些情况,将字符串中的所有第一个字母大写?

时间:2019-12-02 19:35:10

标签: javascript capitalization

这是我到目前为止所做的。我将所有单词的首字母大写。

预期产量:母牛跳舞

我收到的输出是: Dance By Cow

let capitalize = str => {
   return str
     .toLowerCase()
     .split('-')
     .map(s => s.charAt(0).toUpperCase() + s.substring(1))
     .join(' ');
};

toTitleCase('dance-by-cow');

3 个答案:

答案 0 :(得分:2)

这样的事情怎么样?

const stopwords = new Set (['by', 'with', 'to', 'from', 'and', 'the'])

然后...

.map(s => stopwords.has(s) ? s : s.charAt(0).toUpperCase() + s.substring(1))

在此级别上,这只是条件代码。但是,获得正确的停用词并不是一件容易的事。

答案 1 :(得分:0)

我猜你在正确的轨道上。也许一个好的解决方案是创建一个exceptions数组,其中包含要从将第一个char转换为大写字母时要跳过的特定单词。

请找到扩展的解决方案:

const toTitleCase = (value) => {
  const exceptions = ['by']; // handling the specific words
  const handleMapping = s => exceptions.includes(s) ? s : s.charAt(0).toUpperCase() + s.substring(1);
  
  return value.toLowerCase()
    .split('-')
    .map(handleMapping)
    .join(' ');
}

console.log(toTitleCase('dance-by-cow'));

我希望这会有所帮助!

答案 2 :(得分:0)

可以尝试使用,例如,使用第二个参数来提供排除词,因为您没有在帖子中指定其他任何词。

function toTitleCase(input, exclusions = []) {
  return input
    .toLowerCase()
    .split('-')
    .map((word) => {
      return exclusions.includes(word) ? word : word.charAt(0).toUpperCase() + word.substring(1);
    })
    .join(' ');
}

let example = toTitleCase('dance-by-cow', ['by']);

console.log(example);