Capitalize the first letter

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
<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

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

Full Source Code

Output: “This is a test”
Capitalize the first character of all words

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
<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”