re: Capitalize the first letter of every word VIEW POST


Case conversion can get a bit tricky with edge cases, like does "one.two" have one word or two, and what of words separated by tabs or newlines.
Often using a regular expression is the way to go.

Can I suggest something like this code, based on a small regex...

toTitleCase = sentence => sentence.replace(
  firstCharOfWord => firstCharOfWord.toUpperCase()

Regular expressions have a builtin assertion \b which can be used to detect word boundaries. The regex /\b[a-z]/ will match wherever the first letter of any word is lowercase. i.e. wherever a word boundary (i.e. not a letter, number or underscore) is followed by a lowercase letter.

String.replace takes a function that cleanly provides uppercased replacements for the matching letters.
I'm guessing this will be faster, though I haven't done benchmarking. It certainly does fewer calls to toUpperCase


I added your function to the benchmark site linked by @aminnairi
Benchmark hello world

Regex seems to performance the fastest... mostly. I'm not really sure how that site samples it's benchmark but it seems awfully fast, meaning few iterations? Having done roughly 30 iterations by hand your regex seems to be ~5-10% faster than the split-map-join. Sometimes the split-map-join is faster though, by a small margin. This is for "hello world" though. Once you start to use longer sentences, your regex becomes the clear winner by a huge margin (roughly 30-40% faster).
Benchmark with longer sentence


Hey thanks for that, that's awesome!

One nice thing about the regex way is that it targets the letters it needs to capitalize. I added test cases for an already capitalized sentence and toTitleCase gets a 400% speedup compared to the non-capitalized sentence (since it won't call toUpperCase if it doesn't need to). The others didn't get any speed up (their code could be tweaked, but I don't think there's a way to get such a boost).
Benchmark here


I really liked this solution. Thanks for writing it.

Code of Conduct Report abuse