Skip to content

Instantly share code, notes, and snippets.

@umair-khanzada
Created March 25, 2020 14:01
Show Gist options
  • Save umair-khanzada/4b39425c4a0a7808376a9237a08e9cf3 to your computer and use it in GitHub Desktop.
Save umair-khanzada/4b39425c4a0a7808376a9237a08e9cf3 to your computer and use it in GitHub Desktop.
Capitalize string eg: (Title, Name, etc) and remove unnecessary spaces between the words
function capitalizeString(str = "") {
// Break name into word's chunk.
let words = str.split(' ');
// Removed empty string, null, undefined, etc.
let filteredWords = words.filter(word => word);
// Capatilize words.
let capatilizeWords = filteredWords.map(word => `${word[0].toUpperCase()}${word.slice(1)}`);
// Concatenate words.
return capatilizeWords.join(' ');
}
// Example
capitalizeString("test user") // "Test User"
capitalizeString("umair, ahmed khanzada") // "Umair, Ahmed Khanzada"
capitalizeString("super admin") // "Super Admin"
capitalizeString("blah blah blah") // "Blah Blah Blah"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment