0

I know there's a javascript solution for this problem, but how can I do this in Coffeescript? e.g. "HELLO" -> "Hello".

I have this so far, but I'm not sure on how to make it work for multiple words:

titleCase = (str) ->
    str[0].toUpperCase() + str[1..str.length-1].toLowerCase()
Community
  • 1
  • 1
2rs2ts
  • 10,662
  • 10
  • 51
  • 95
  • Coffeescript is javascript. It would be the exact same, just in coffeescript. – Fresheyeball Dec 04 '13 at 16:46
  • @Fresheyeball I'm new to Coffeescript, so I wasn't able to obviously see the conversion. I am aware of this, though. – 2rs2ts Dec 04 '13 at 17:09
  • @Fresheyeball While it's true that coffeescript is javascript, it's often possible to write something more concise than a 1-to-1 translation in coffeescript by making use of its idioms. For instance, it's possible to reduce `str[1..str.length-1]` to `str[1..-1]`. – Tim Oct 24 '14 at 21:00

1 Answers1

3

This would be an almost 1:1 conversion from your linked answer.

toTitleCase = (str) ->
    str.replace /\w\S*/g, (txt) -> # see comment below
        txt[0].toUpperCase() + txt[1..txt.length - 1].toLowerCase()

The second line uses the regex version of replace - any occurrence of letters followed by a space will be matched and replaced with the result of calling the following function with the matched string.

Zeta
  • 103,620
  • 13
  • 194
  • 236
  • Shoot, I was thinking CoffeeScript had the same functions in Ruby! I was using `.upcase` and `.downcase`! – Chloe Jan 15 '16 at 21:49