How to capitalize all words in a string using JavaScript? How to make first letter uppercase?

How do I make the first letter of all words in a string uppercase? I want to capitalize all words, like what PHP ucwords() do. I don’t find any function like that in javascript. We have the toUpperCase() function which makes everything uppercase but why can’t we make all words capitalized?

Is there any way to make a function that I can directly call on the string variable? For example.

var simpleString = "this is a simple string";
console.log( simpleString.ucwords() );
// This Is A Simple String

How to implement ucwords() in JavaScript?

We don’t know why JavaScript does not have any function like that. Maybe in the future, they will add the function. Till now we have to use a custom function to fulfill the need.

String.prototype.toCapitalize = function( allowAll = true ){
    return allowAll ? this.split(' ').map( word => word.toCapitalize(false) ).join(' ') : 
    this.charAt(0).toUpperCase() + this.slice(1);
}

This will fulfill your goal.

var simpleString = "this is a simple string";
console.log( simpleString.toCapitalize() );
// This Is A Simple String

Anyway you can change the function name from toCapitalize() to ucwords()