Last active
February 3, 2018 20:35
-
-
Save GreggSetzer/5077099435c668e1e9c51aca3722b87f to your computer and use it in GitHub Desktop.
Javascript Interview Question: Title Case - Capitalize the first letter in each word of a string.
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
/* | |
Create a function that accepts a string, converts the string to title case, and | |
returns the result. For title case, the first letter of each word is capitalized. | |
capitalize('hello world'); //Outputs: 'Hello World' | |
captialize('the year of the hare'); //Outputs: 'The Year Of The Hare'; | |
Pseudo code: | |
1. Split the string into array using str.split(' '); | |
2. Map over the elements in the array. Title case each word using helper function. | |
3. Join the elements of the newly defined array separated by space. | |
4. Return the result. | |
*/ | |
function capitalize(str) { | |
return str.split(' ').map(word => titleCase(word)).join(' '); | |
} | |
//Helper function to capitalize a single word. | |
function titleCase(word) { | |
return word[0].toUpperCase() + word.slice(1); | |
} | |
//Try it | |
console.log(capitalize('arto paasilinna')); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment