Title Case A Sentence JavaScript

Let's say we are required to write a function that accepts a string and capitalizes the first letter of every word in that string and changes the case of all the remaining letters to lowercase.

For example, if the input string is ?

hello world coding is very interesting

The output should be ?

Hello World Coding Is Very Interesting

Let's define a function capitaliseTitle() that takes in a string and capitalises the first letter of each word and returns the string ?

Using Split and Map Method

let str = 'hello world coding is very interesting';

const capitaliseTitle = (str) => {
    const string = str
        .toLowerCase()
        .split(" ")
        .map(word => {
            return word[0].toUpperCase() + word.substr(1, word.length);
        })
        .join(" ");
    return string;
}

console.log(capitaliseTitle(str));

Output

Hello World Coding Is Very Interesting

Using Regular Expression

Another approach is to use regular expressions with the replace method:

let str = 'hello world coding is very interesting';

const capitalizeWithRegex = (str) => {
    return str.toLowerCase().replace(/\b\w/g, char => char.toUpperCase());
}

console.log(capitalizeWithRegex(str));

Output

Hello World Coding Is Very Interesting

Comparison

Method Approach Performance Readability
Split and Map Array manipulation Good for short strings More explicit
Regular Expression Pattern matching Better for long strings More concise

Conclusion

Both methods effectively convert strings to title case. The split-map approach is more readable, while the regex method is more concise and efficient for longer strings.

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

330 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements