Skip to content

Instantly share code, notes, and snippets.

@guillaumepotier
Last active February 14, 2019 08:52
Show Gist options
  • Save guillaumepotier/5a5cbafbf493afdb26ec5a1e14c3ec0b to your computer and use it in GitHub Desktop.
Save guillaumepotier/5a5cbafbf493afdb26ec5a1e14c3ec0b to your computer and use it in GitHub Desktop.
Capitalize Game
// Aim of this game is to capitalize every name (even composed ones) the more efficiently possible
// use regex to recursively capitalize every letter preceded by " " or "-" *and* first char too
const capitalized = string => string.replace(/(^|\s|-)([a-z])/g, letter => letter.toUpperCase());
// Thomas-Louis-Joseph-Simon Raymond Jean Claude T-Y Ty T-Fd
console.log(capitalized("thomas-louis-joseph-simon raymond jean claude t-y ty t-fd"));
@tomplays
Copy link

fix :
var capitalized = string.charAt(0).toUpperCase() + string.slice(1);

@CipicReborn
Copy link

my workmate Jean indicates that the regex can be improved to detect the first character also by adding ^ to the detection pattern :

capitalized = capitalized.replace(/(^|\s|-)([a-z])/g, function(letter) {
  return letter.toUpperCase();
});

which allows to delete the lines

// capitalize first letter
var capitalized = capitalized.charAt(0).toUpperCase() + capitalized.slice(1);

@guillaumepotier
Copy link
Author

@tomplays @CipicReborn thanks. Now using ES6 syntax its even prettier ;)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment