How to Title Case a sentence in JavaScript?

Title case formatting converts the first letter of each word in a sentence to uppercase while keeping the remaining letters lowercase. This is commonly used for headings, titles, and proper formatting of text.

Algorithm

  • Split the sentence into individual words using string.split() method
  • Convert all letters in each word to lowercase using string.toLowerCase() method
  • Loop through each word and capitalize the first letter using toUpperCase()
  • Concatenate the capitalized first letter with the remaining lowercase letters
  • Join all words back together using array.join() with spaces

Using Manual String Manipulation

<html>
<body>
<script>
    function titleCase(string) {
        var sentence = string.toLowerCase().split(" ");
        for(var i = 0; i < sentence.length; i++){
            sentence[i] = sentence[i][0].toUpperCase() + sentence[i].slice(1);
        }
        document.write(sentence.join(" "));
        return sentence.join(" ");
    }
    
    titleCase("tutorix is one of best e-platforms");
</script>
</body>
</html>
Tutorix Is One Of Best E-platforms

Using Array Map Method

<html>
<body>
<script>
    function titleCaseMap(string) {
        var result = string.toLowerCase()
            .split(" ")
            .map(function(word) {
                return word.charAt(0).toUpperCase() + word.slice(1);
            })
            .join(" ");
        
        document.write(result);
        return result;
    }
    
    titleCaseMap("javascript programming tutorial");
</script>
</body>
</html>
Javascript Programming Tutorial

Using Regular Expression

<html>
<body>
<script>
    function titleCaseRegex(string) {
        var result = string.toLowerCase().replace(/\b\w/g, function(letter) {
            return letter.toUpperCase();
        });
        
        document.write(result);
        return result;
    }
    
    titleCaseRegex("learn web development online");
</script>
</body>
</html>
Learn Web Development Online

Comparison

Method Readability Performance Best For
Manual Loop Good Fast Simple cases
Array Map Excellent Good Functional programming
Regular Expression Good Very Fast Complex text processing

Conclusion

Title case conversion can be achieved through multiple approaches in JavaScript. The regular expression method is most efficient, while the array map approach offers better readability for functional programming styles.

Updated on: 2026-03-15T23:18:59+05:30

10K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements