Skip to content

Instantly share code, notes, and snippets.

@GreggSetzer
Last active February 3, 2018 20:35
Show Gist options
  • Save GreggSetzer/5077099435c668e1e9c51aca3722b87f to your computer and use it in GitHub Desktop.
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.
/*
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