JavaScript: Convert a String to Title Case

1. Introduction

A common task in text processing is to convert a string to a title case. This ensures the first letter of each word in the string is capitalized, while the rest are in lowercase.

2. Program Overview

We will create a function named toTitleCase that takes a string as its parameter. The function will process each word in the string and capitalize its first letter. Finally, the function will return the transformed string.

3. Code Program

// Function to convert a string to title case
function toTitleCase(str) {
    // Split the string into an array of words
    let wordsArray = str.toLowerCase().split(' ');

    // Convert the first letter of each word to uppercase
    let resultArray = wordsArray.map(word => {
        return word.charAt(0).toUpperCase() + word.slice(1);
    });

    // Join the array back into a string and return
    return resultArray.join(' ');
}

// Test the function
let example1 = toTitleCase('hello world');  // Expected: 'Hello World'
let example2 = toTitleCase('JaVascRIpt pRogramMing');  // Expected: 'Javascript Programming'

console.log(example1);
console.log(example2);

Output:

Hello World
Javascript Programming

4. Step By Step Explanation

1. Function Definition: We start by defining a function named toTitleCase that accepts a string as its parameter.

2. String Transformation: Inside the function, we first convert the entire string to lowercase to ensure uniformity. Then, we split this string into an array of words using the split method.

3. Capitalize Each Word: We then use the map function on the array of words. For each word, we capitalize its first letter and append the rest of the word. This gives us a new array with the transformed words.

4. Final Result: Finally, we join the transformed words back together into a string using the join method and return the result.

5. Tests: We test our function with two example strings. The first test uses a simple lowercase string, while the second test uses a string with inconsistent capitalization.

This program showcases how to effectively use string and array methods in JavaScript to process and transform text data.

Comments