Coding Article Detail

post featured image

How to Title Case a Sentence in JavaScript (with code)

This programming exercise shows how to convert the first letter of each word in a sentence to uppercase while the other letters remain in lowercase. We pass a sentence(string) that may contain a mix of lowercase and uppercase letters. So we need an algorithm to Title Case the provided sentence.

Algorithm:

Create an empty array.
Divide the words in the sentence using string.split() method.
Convert all the letters in each word to lowercase using string.toLowerCase() method.
Loop through all the words in the sentence using for loop and convert the first letter of each word to uppercase and concatenate them with the remaining letters of their respective word, obtaining the original word with first letter in uppercase.
Join all the words using string.join() with a space between them so that we get the original sentence but capitalized.

Here's an example of how you can use this formula to capitalize a sentence in JavaScript:
<code>
function titleCase(sentence) {
let result = [];
sentence = sentence.toLowerCase().split(" ");
for (let word of sentence) {
result.push( word[0].toUpperCase() + word.slice(1))
}
return result.join(" ");
}

tittleCase( "i'Ve bEen cApitaLized");

This will output the following:

"I've Been Capitalized";

By joseguerra on Thu 01 Dec 2022

Last updated 1 year, 9 months ago
Category: JavaScript
1 1

Back to Coding Articles

Comments: 1

johndoe on Sat 07 Jan 2023 wrote:

thank you for the article !

Would you like to leave a comment?. Already have an account? Then please Sign In

If you don't have an account please Sign Up to create one.