How To Capitalize First Letter Of Each Word In Js ?

By using function:

“replace()” is a iterative function calling a regex as first parameter and adding callback function as its second parameter we can achieve this.

Regular Expression for Every Word in a String ( /\w\S*/g )

And

Callback function converts first word of every word to Upper case

var text = "how to capitalize first letter of each word in js ?";

function toTitleCase(str) {
    return str.replace(/\w\S*/g, function(txt){
        return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();
    });
}

text = toTitleCase(text);

//output
//How To Capitalize First Letter Of Each Word In Js ?

For es6:

var text = "how to capitalize first letter of each word in js ?";

upperCaseWords = (s => s.toLowerCase().split(" ").map(s => s.charAt(0).toUpperCase() + s.substring(1)).join(" "));
    
text = upperCaseWords(text)

//output
//How To Capitalize First Letter Of Each Word In Js ?

Leave a Reply

Your email address will not be published. Required fields are marked *