Algorithm
- Input: Accept a string as input.
- Check for Empty String: Ensure that the input string is not empty.
- Extract the First Letter: Get the first character of the input string.
- Convert to Uppercase: Use the
toUpperCase()
method to convert the first letter to uppercase. - Concatenate: Concatenate the uppercase first letter with the rest of the string (excluding the first character).
- 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
Enter a string: javaScript
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
Enter a string: javaScript
JavaScript
JavaScript
Demonstration
JavaScript Programing Example to Convert the First Letter of a String into UpperCase-DevsEnv