Javascript - Capitalize string

By xngo on August 21, 2019

Here is a simple JavaScript function to capitalize a string. Please note that strings are immutable. That is why I have to concatenate the first character with the rest of the string to form the result.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Javascript - Capitalize</title>
    <script>
 
        function capitalize(str) {
            firstChar = str.charAt(0).toUpperCase();
            result = firstChar + str.substring(1);
            return result;
        }
 
        input="test";
        alert( capitalize(input) );
    </script>
</head>
<body>
 
</body>
</html>

Output

It is will pop up an alert with the string Test.

Js - capitalize function output

About the author

Xuan Ngo is the founder of OpenWritings.net. He currently lives in Montreal, Canada. He loves to write about programming and open source subjects.