capitalize('a short sentence') //--> 'A Short Sentence'
capitalize('a lazy fox') //--> 'A Lazy Fox'
capitalize('look, it is working!') //--> 'Look, It Is Working!'
My Solution
function capitalize(str) {
return str.replace(/(^\w|\s+\w)/g, (match) => match.toUpperCase());
}
SG Solution
function capitalize(str) {
let result = str[0].toUpperCase();
for (let i = 1; i < str.length; i++) {
if (str[i - 1] === ' ') {
result += str[i].toUpperCase();
} else {
result += str[i];
}
}
return result;
}