The Ultimate Guide to JavaScript Algorithms - Lesson #7

JavaScript Algorithms: 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.

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

capSentence('the tales of arise!') // would return 'The Tales Of Arise!'

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?

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()

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, 'candy.']

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.

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 =>{
        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.

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 = 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.

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()

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.

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.

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.

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

See you in the next one!✌🏿

Want to improve your coding and design skills?

I'm continually researching the best practices and tools for coding.
Join 50,000+ developers looking to make cool stuff.

We value your privacy. 1-click unsubscribe.


What did you think of the article? Let us know!
(these comments are powered by GitHub issues and use 0 trackers)