Due to the apparent complexity of something so simple I thought I'd explain myself here. I originally started with the obvious, which most searches for "[javascript word count](https://www.google.co.uk/search?q=javascript+word+count)" will suggest:

``` coffeescript
text.split(/\s+/).length
```

I quickly realised that this wouldn't work properly when there is leading/trailing white space so I trimmed the `text` first:

``` coffeescript
text.trim().split(/\s+/).length
```

I was happy with this for quite a while until I remembered that `split` will always return an array containing at least one string - the one being split. So if `text` was an empty string, this logic would count that as 1 word, so I had to add change the logic again:

``` coffeescript
text = text.trim()
if text then text.split(/\s+/).length else 0
```

Done! Or so I thought. It occurred to me that, since this could potentially be used to count the words on very long pieces of text (e.g. a whole page), I should probably check performance of `split` against `match` and I'm very glad I did.

First, I [created test cases](http://jsfiddle.net/alasdair/d3KGy/) for various different methods I came up with to determine word count to ensure they worked correctly.

Finally, I [tested the performance](http://jsperf.com/word-count-test) of each solution to determine which worked best. The solutions varied greatly across browsers but Chrome definitely favoured this approach. When I finally get around to porting Template to other browsers I'll need to reconsider this for each browser, but for now, this is the way we're doing it.