The Ultimate Guide to JavaScript Algorithms

Sentence Capitalization

Sentence Capitalization

Often times, situations arise in which we need to manipulate the letter casing of stings within our applications usually for presentational purposes. JavaScript offers two popular methods designed for such purposes:

  • .toUpperCase() This method returns the string passed in as an argument converted to uppercase letters.
  • .toLowerCase() This method returns the string passed in as an argument converted to lowercase letters.

Is this sufficient? Since these methods transform all letters to either uppercase or lowercase, how would one implement capitalization as shown in the sentence below?

How To Implement Sentence Capitalization Algorithm In JavaScript.

In this article, we will explore various approaches to doing this.

You should already have your development environment setup for this course. Update your cloned repository by running the command git pull. Inside the Beginner folder, navigate to the capSentence folder. Our work for this challenge will be done in here. Make sure to follow along in the index-START.js file.

The Challenge

Given a sentence containing two or more words, return the equivalent of the sentence when capitalized. E.g

capSentence('the tales of scotch!') // would return 'The Tales Of Scotch!'

Algorithmic Thinking

At a glance this may seem like a very simple challenge, but it actually isn’t when considered carefully.

Working through the challenge statement, we see that we would need to write a function that'd receive the sentence to be converted as an argument. Next, we are to go through every word in the sentence and capitalize the first letter only. This brings to mind the concept of loops.

How do we get this done? .toUpperCase(), .toLowerCase() or something else?

Code Implementation

Definitely something else. We shall now explore three ways to solve this challenge. They are;

  • Using the .forEach() method
  • Using .map() and .splice()
  • Using .map() and .replace()

Using .forEach() Method

The **.forEach()** method in JavaScript runs a provided function on each element within an array.

Here's how we do this:

function capSentence(text) {
    let wordsArray = text.toLowerCase().split(' ')
    let capsArray = []

    wordsArray.forEach(word => {
        capsArray.push(word[0].toUpperCase() + word.slice(1))
    });

    return capsArray.join(' ')
}

Notice how we call the .toLowerCase() method on the string of text received to convert the entire sentence to lowercase. We also chain the .split() method in sequence to divide the lowercase sentence into an array of words as shown below. This array is stored as wordsArray.

wordsArray = ['this', 'one', 'is', 'for, 'scotch.']

Next, using the .foreach() method, we iterate through every word(element) in the array and execute a function on it. The function takes the first letter of the word and turns it to uppercase using the .toUpperCase() method. To retrieve the remaining part of the word in lowercase, we use the .slice() method to slice the string starting from position 1 till the end.

**.slice()** when used on a string extracts a section of the string and returns it as a new string. It receives two arguments; the beginning index which is compulsory and the end index which is only optional.

We combine the transformed first letter and the sliced section together to form the capitalized word which we push into our array of capitalized words capsArray.

After this process has being carried out for every word, capsArray now holds the capitalized version of every word in the sentence.

Finally, we combine each word(element) using the .join() method. We pass in an empty space as the separator. This gives us the capitalized sentence which we return in conclusion.

Let's see another approach.

Using .map() and .slice()

The .map method is used to create a new array with the results gotten from calling a provided function on every element in the array on which it is called.

Here's our implementation:

function capSentence(text) {
    let wordsArray = text.toLowerCase().split(' ')
    let capsArray = wordsArray.map(word=>{
        return word[0].toUpperCase() + word.slice(1)
    })
    return capsArray.join(' ')
}

We use the same technique as before to create wordsArray, an array of all words in the lowercase sentence.

This time we use the .map() function to loop through every word in the array and execute the same function as before in order to create capsArray, which is an array of the capitalized words.

In the end we return a capitalized sentence created by joining the words in the capsArray with blank space as the separator.

This may seem like an only slightly different approach, however it is necessary for us to consider this too as our objective is to determine what method performs better despite the similarities.

Let’s consider one final approach.

Using .map() and .replace()

In this approach we use the .map() method as above to execute a function on every word(element) in the wordsArray.

In this function, we populate our capsArray differently with the use of the .replace() method.

.replace() is used to create a new string with some or all matches of a **pattern** replaced by a **replacement**. The pattern and replacement are passed in as arguments when this method is called.

Here’s how we use this:

function capSentence(text) {
    let wordsArray = text.toLowerCase().split(' ')

    let capsArray = wordsArray.map( word=>{
        return  word.replace(word[0], word[0].toUpperCase())
    })

    return capsArray.join(' ')
    }

Notice that we replace the first letter of each word(word[0]) with an uppercase version of this same letter. Then we add the capitalized word using the .push() method to the capsArray.

Conclusively, we return the capitalized sentence formed as in the previous cases.

Now let's test these out.

Testing

Testing Correctness with Jest

When we run our tests using the command below, we get the results shown below.

npm run test capSentence
  • Using .forEach() method

  • Using .map() and .slice()

  • Using .map() and .replace()

Testing Performance on JSPerf

Follow this link to find a performance comparison of each solution considered above.

Here's the result of our comparison:

As always, you are advised to run these tests yourself to see that you get similar results.

Our test reveals that using the .map() and .slice() method is the fastest. Next, is .forEach() which is approximately 15% slower. And last, is the .map() and .replace() which is 29% slower.

Practical Application

This challenge could be encountered when trying to title case a sentence using JavaScript in real world applications. Also it is often used as a challenge for JavaScript interviews.

Conclusion

In solving this challenge, we have learnt more techniques for manipulating arrays and strings.

More-so, we have considered three ways to title case a sentence in JavaScript and we have determined using the .map() and .slice() method to be the most optimal.

There are definitely more ways to go about this so feel free to explore them, compare them performance-wise and share in the comment section.

Further Reading

To learn more about the methods and concepts highlighted in this article, you may use the links below:

See you in the next one!✌🏿

Like this article? Follow @worldclassdev on Twitter