How to capitalize first letter of a string with JavaScript

"hello world" => "Hello world"

String.prototype.capitalizeFirst = function()
{
    return string.charAt(0).toUpperCase() + string.slice(1);
}

// example
"hello world".capitalizeFirst(); //Output: Hello world

To convert a sting to title case with JavaScript check : How to convert a sting to title case with JavaScript

For who do not like prototype here is a Non prototype version for the same:-

function capitalizeFirst(string) 
{
    return string.charAt(0).toUpperCase() + string.slice(1);
}

// example
toTitleCase("hello world"); // Output : Hello world

For this solution we used:

  • The charAt() function returns the specified character from a string.
  • The toUpperCase() function returns the calling string value converted to uppercase
  • The slice() function extracts a section of a string and returns a new string.

How to convert a sting to title case with JavaScript

"hello world" => "Hello World"

We can convert a string to title case with below JavaScript function

String.prototype.toTitleCase = function()
{
    return this.replace(/\w*/g, function(str){return str.charAt(0).toUpperCase() + str.substr(1).toLowerCase();});
}
"hello world".toTitleCase(); // Output : Hello World

To capitalize only first letter with JavaScript check : How to capitalize first letter of a string with JavaScript

For who do not like prototype here is a Non prototype version for the same:-

function toTitleCase(string)
{
    return string.replace(/\w*/g, function(str){return str.charAt(0).toUpperCase() + str.substr(1).toLowerCase();});
}
   toTitleCase("hello world"); // Output : Hello World

Extra : Looking for angular solution read here : Angular TitleCase