Skip to content

Instantly share code, notes, and snippets.

@eldyvoon
Last active January 3, 2018 04:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save eldyvoon/b9ca42d78b0feda51ab5827a94a7cbce to your computer and use it in GitHub Desktop.
Save eldyvoon/b9ca42d78b0feda51ab5827a94a7cbce to your computer and use it in GitHub Desktop.
Sentences capitalization in JavaScript
//spec
capitalize('my mom is cooking') // My Mom Is Cooking
capitalize('wait, I'm coming!') // Wait I'm Coming!
//solution 1
function capitalize(str) {
const words = [];
for(let word of str.split(' ')){
words.push(word[0].toUpperCase() + word.slice(1))
}
return words.join(' ');
}
//solution 2
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;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment