JavaScript - Capitalize First letter



Return the provided string with the first letter of each word capitalized. Make sure the rest of the word is in lower case. For the purpose of this exercise, you should also capitalize connecting words like "the" and "of".


Solution 1 Loop approach


console = { 
    log: print,
    warn: print,
    error: print
};
function titleCase(str) {
    let newStr = str.toLowerCase().split(" ")
    for (let i = 0; i < newStr.length; i++) {
        newStr[i] = (newStr[i][0].toUpperCase() + newStr[i].slice(1))
    }
    newStr = newStr.join(" ")
    return newStr;
}
console.log(titleCase("I'm a liTtle tea pot"));

Output:


I'm A Little Tea Pot

Solution 2 Basic approach


console = { 
    log: print,
    warn: print,
    error: print
};
function titleCase(str) {
    var word = str.toLowerCase().split(" ")
    word[0] = word[0].toUpperCase();
    str = word.join(' ');
    return str;
}
console.log(titleCase("I'm a liTTle tea pot"));

Output:


I'm A Little Tea Pot

Solution 3 map approach


console = { 
    log: print,
    warn: print,
    error: print
};
function titleCase(str) {
    var convertToArray = str.toLowerCase().split(" ");
    var result = convertToArray.map(function (val) {
        return val.replace(val.charAt(0), val.charAt(0).toUpperCase());
    });
    return result.join(" ");
}
console.log(titleCase("I'm a little tea pot"));

Output:


I'm A Little Tea Pot

Solution not working or have any suggestions? Please send an email to [email protected]



Join Our Facebook Group


Share this example


Download Android App

download android app

Popular javascript Examples









codesadda.com

Codesadda.com is your home of programming solutions, tutorials, video tutorials and much more. Sign Up for our weekly newsletter to get update about new content.

Like us on Facebook | Connect with us on LinkedIn | Subscribe our Channel on Youtube