Capitalize the first letter
![](https://www.corelangs.com/wp-content/uploads/2024/05/left.png)
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
![](https://www.corelangs.com/wp-content/uploads/2024/05/trim-2.png)
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
![](https://www.corelangs.com/wp-content/uploads/2024/05/uppercase1.png)
Full Source Code
![](https://www.corelangs.com/wp-content/uploads/2024/05/uppercase2.png)
Output: “This is a test”
Capitalize the first character of all words
![](https://www.corelangs.com/wp-content/uploads/2024/05/switch.png)
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”