Capitalize the first letter of the given word
javascript
Instructions:
Take the variable str
and capitalize the first letter of the word. Put the result in a variable called newStr
.
Expected result:
const str = 'javascript'
console.log(newStr); // Javascript
Solution:
const str = 'javascript';
// default value
let newStr = '';
if (str && isNaN(str)) {
// If str is not empty, get the first char, capitalize and concatenate it with the rest of the string
if (str.length > 0) {
// if str has more than one char
newStr = str.charAt(0).toUpperCase() + str.slice(1);
} else {
// if str has only one char
newStr = str.toUpperCase();
}
}
console.log(newStr);
Same solution using ES6 syntax:
const str = 'javascript';
let newStr = str && isNaN(str)
? str.length > 0
? str.charAt(0).toUpperCase() + str.slice(1)
: str.toUpperCase()
: '';
console.log(newStr);
Test Values:
str = 'javascript'; // Javascript
str = 'Javascript'; // Javascript
str = 'a'; // A
str = ''; // ''
str = null; // ''
str = undefined; // ''
str = 1234; // ''