Last active
January 3, 2018 04:58
-
-
Save eldyvoon/b9ca42d78b0feda51ab5827a94a7cbce to your computer and use it in GitHub Desktop.
Sentences capitalization in JavaScript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//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