Algorithm


  1. Input: Accept a string as input.
  2. Check for Empty String: Ensure that the input string is not empty.
  3. Extract the First Letter: Get the first character of the input string.
  4. Convert to Uppercase: Use the toUpperCase() method to convert the first letter to uppercase.
  5. Concatenate: Concatenate the uppercase first letter with the rest of the string (excluding the first character).
  6. Output: Return the resulting string as the output.

 

Code Examples

#1 Code Example- Convert First letter to UpperCase

Code - Javascript Programming

// program to convert first letter of a string to uppercase
function capitalizeFirstLetter(str) {

    // converting first letter to uppercase
    const capitalized = str.charAt(0).toUpperCase() + str.slice(1);

    return capitalized;
}

// take input
const string = prompt('Enter a string: ');

const result = capitalizeFirstLetter(string);

console.log(result);
Copy The Code & Try With Live Editor

Output

x
+
cmd
Enter a string: javaScript
JavaScript

#2 Code Example- Convert First letter to UpperCase using Regex

Code - Javascript Programming

// program to convert first letter of a string to uppercase
function capitalizeFirstLetter(str) {

    // converting first letter to uppercase
    const capitalized = str.replace(/^./, str[0].toUpperCase());

    return capitalized;
}

// take input
const string = prompt('Enter a string: ');

const result = capitalizeFirstLetter(string);

console.log(result);
Copy The Code & Try With Live Editor

Output

x
+
cmd
Enter a string: javaScript
JavaScript
Advertisements

Demonstration


JavaScript Programing Example to Convert the First Letter of a String into UpperCase-DevsEnv

Previous
JavaScript Practice Example #3 - Assign 3 Variables and Print Good Way