0

我正在创建一个 APA titleCase 函数,并且试图弄清楚如何将不重要的单词(the、a、an 等)大写。到目前为止,我只知道如何将所有小单词大写或小写,即使是应该大写的小单词。我试图将不重要的小词保持大写。例如,标题的第一个单词,以及后面跟冒号和连字符的单词来命名一些。如果将“此标题是 JavaScript 的示例标题:第一卷”的标题对象传递给函数,我需要它返回为“此标题是 JavaScript 的示例标题:第一卷”。有人可以帮助保持小写字母。

function titleCase(title) {

  title.toLowerCase();
  var smallWords = ['a', 'an', 'and', 'as', 'at', 'but', 'by', 'en', 'for', 'if', 'in', 'nor', 'of', 'on', 'or', 'per', 'the', 'to'];
  var titleSplit = title.split(' ');

  for (var i = 0; i < titleSplit.length; i++) {
    if (titleSplit[i] === titleSplit[0]) {
      titleSplit[i] = titleSplit[i].charAt(0).toUpperCase() + titleSplit[i].slice(1);
    } else if (titleSplit[i] === 'api' || titleSplit[i] === 'Api') {
      titleSplit[i] = 'API';
    } else if (titleSplit[i] === 'javascript' || titleSplit[i] === 'Javascript') {
      titleSplit[i] = 'JavaScript';
    } else if (smallWords.includes(titleSplit[i])) {
      titleSplit[i] = titleSplit[i].toLowerCase();
    }

  }

  title = titleSplit.join(' ');

  title = title.replace(/(?:^|[\s-/])\w/g, match => {
    return match.toUpperCase();
  });

  console.log('title:', title);

  return title;
}
4

1 回答 1

0

这是我的做法。

const titleCase = string => {
    const doNotCapitalize = ['a', 'an', 'the', 'at', 'by', 'for', 'in', 'of', 'on', 'to', 'up', 'and', 'as', 'but', 'or', 'nor'];
    const words = string.split(' '); // array
    const numOfWords = words.length - 1;
    return string
        .toLowerCase()
        .split(' ')
        .map((word, i) => {
            // capitalize the first and last word regardless
            if (i === 0 || i === numOfWords) {
                return word.replace(word[0], word[0].toUpperCase());
            }
            return doNotCapitalize.includes(word) ? word : word.replace(word[0], word[0].toUpperCase());
        })
        .join(' ');
};
于 2022-01-21T04:11:37.883 回答