0

I'm creating an APA titleCase function, and I'm trying to figure out how to uppercase non-important words(the, a, an, etc). So far I've only figured out how to either uppercase or lowercase all small words, even small words that should be capitalized. I'm trying to keep small words that are not non-important words capitalized. For example, the first word of a title, and words followed by a colon and hyphen to name some. If a title object of "this title is An Example title For Javascript: volume-one," is passed into the function, I need it to return as "This Title is an Example Title for JavaScript: Volume-One." Can someone please help keep the small words lowercased.

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;
}
JB49er
  • 15
  • 3
  • You have your words split with a space, then uppercase the first letter. What's your question ? – sln Jan 20 '22 at 21:27
  • Sorry, my concern must have gotten cut off. I can uppercase the first letters of words of the title but the non-important words are also uppercased, and I'm trying to keep the non-important words lowercased, if they are not the first word of the title. – JB49er Jan 20 '22 at 22:23

1 Answers1

0

Here's how I do it.

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(' ');
};
Matt Rose
  • 526
  • 2
  • 6
  • 14