Capitalize the first letter

Javascript first letter capital

It is so easy to capitalize the first word of a string in Javascript. The following Javascript function will change the first word of a string to capitalize.

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

Full Source Code

<html> <body> <script type="text/javascript"> var str = "this is a test"; document.write( titleCase(str) ); function titleCase(string) { return string.charAt(0).toUpperCase() + string.slice(1); } </script> </body> </html>

Output: "This is a test"

Uppercase first letter in a string usinf RegEx

Capitalize all words in a string in javascript

You can capitalize the first letter of a string by using RegEx also. The following program shows how to change the first letter of a string to upper case using RegEx. The following function change the first letter to capital using RegEx

Javascript title case

Full Source Code

Makes the first letter caps and the rest lowercase

Output: "This is a test"

Capitalize the first character of all words

How To Capitalize First Letter In Text Field

In some situations we have to capitalize the first character of all words in string. The following function change first character to capital letter to all words in string.

function allTitleCase(inStr) { return inStr.replace(/\w\S*/g, function(tStr) { return tStr.charAt(0).toUpperCase() + tStr.substr(1).toLowerCase(); }); }

Full Source Code

<html> <body> <script type="text/javascript"> var str = "this is a test"; document.write( allTitleCase(str) ); function allTitleCase(inStr) { return inStr.replace(/\w\S*/g, function(tStr) { return tStr.charAt(0).toUpperCase() + tStr.substr(1).toLowerCase(); }); } </script> </body> </html>

Output: "This Is A Test"