title case converter exercise javascript

Title Case Converter - excluding specific words from being capitalized




Title case converter

If you haven't checked my 'Title Case Converter' yet, you may do it right now. What is a title case?

Title case is a style that is used for the titles of articles, books, movies, songs, and other works. It makes the title look elegant and readable.

So what this program does?

In this exercise, I am writing the function that does title case converting. However, there's a trick.

All major words will be capitalized, while minor words will be lowercased. It means that we capitalize every word except articles, coordinating conjunctions, and others. In my program, I called them specialWords. The special words are saved in the array below.

const specialWords = ['and','an','a','or','the','is','of', 'but','on',];

So what this program does? Please check the example below.

  • INPUT: The man of the forest.
  • OUTPUT: The Man of the Forest.

JavaScript concepts

To write this program, I will use string and array methods. First, we need to convert an input value to lowerCase(). Then I split() a string, which means I convert it to an array.

I loop through this array, checking if the specialWords array includes() any specific word (our input string that I converted). If it does, this specific word will be converted toLowerCase(), if it doesn't, the first character of each word will be converted to upperCase(). Then I convert back the output array to a string with the join() method.

The correctOutput function is a callback function. This function generally corrects the final output but is also called in the ternary operator. Let me explain what it does.

If our input string starts from any of the special words e.g. 'the', our output will be:
the Beginning of the Road, instead of The Beginning of the Road

That's what this function is for. We return the function, passing output – as the argument.

This function will always convert index(0) of our output string to upperCase(), no matter if it's a special word, or not.

In this example, I don't access any DOM elements. It's just a pure function.

If you're interested in checking my application source code, feel free to dive deeper into my Github repository.

const convertString = string => {
    const correctOutput = output => output.at(0).toUpperCase() + output.slice(1);

    const output = string
    .split(' ')
    .map(word => (specialWords.includes(word) ? word : correctOutput(word)))
    .join(' ');

    return correctOutput(output);

    console.log(convertString('The best of the best')); // The Best of the Best
    console.log(convertString('The beginning of the road')); //The Beginning of the Road