4 ms·
While already quite clean, your JavaScript can be simplified somewhat. split() will take a regular expression: var wordCount = value.trim().split(/\s+/).le
by skymt 14y ago
While already quite clean, your JavaScript can be simplified somewhat. split() will take a regular expression:
var wordCount = value.trim().split(/\s+/).length
Additionally, JavaScript's regex dialect has a special character of "\W", which matches any non-word character. So if you split on "\W+" instead, you ought to get a more reliable list of words, eliminating cases like "foo -- bar" counting as 3 words.
- joelrunyon 14y agoThanks Skymt. I'll implement that this weekend. Thanks for the tips.
- ThomasQue 14y agoI was wondering what a word (in a word count) was, thinking like you that "foo -- bar" was only two words, just like "foo-bar" or "foo/bar". So I started two widely used word processors and got surprising results : "foo -- bar" is actually considered 3 words long in both Microsoft Word 2007 and LibreOffice Writer 3.6.1.2, but "foo-bar" and "foo/bar" are 1 word long. There seems to be no standard as to what a word is in this context : Different word counting programs may give varying results, depending on the definition of "word", on the text segmentation algorithms, and on whether words outside the main text such as footnotes or hidden text are counted. [1] Anyway it seems a consensus to say that "foo -- bar" is 3 words long, so wordcount.is does give a not so wrong answer after all. [1] http://en.wikipedia.org/wiki/Word_count http://en.wikipedia.org/wiki/Word_count
- joelrunyon 14y agoHey Skymt, I implemented the first part of your suggestion and it worked well. However, when I tried to implement the \W, it gave me a very different count. When I checked it against Microsoft's Word's count for block of lorem ipsum text, the original function matched it exactly. Any thoughts as to what happened?