HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptMinor

Counting the words in a textarea

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
wordsthecountingtextarea

Problem

I've two working ways to do so, but which one should I use?

Common part: var textarea = document.getElementById("textarea");

First way:

function updateStatusBar() {
    var text = textarea.value;
    statusBar.value = "Words: " + (text ? text.match(/\b\S+\b/g).length : "0") +
      "  Characters: " + text.replace(/\s/g, "").length +
      " / " + text.replace(/\n/g, "").length;
}


and second way:

function updateStatusBar() {
    var text = textarea.value;
    statusBar.value = "Words: " + (text.split(/\b\S+\b/).length - 1) +
      "  Characters: " + text.replace(/\s/g, "").length +
      " / " + text.replace(/\n/g, "").length;
}


Please review the Words: counting code. Which one should I use?

Solution

The key difference between the two approaches is essentially these lines,
counting the words in text:

text ? text.match(/\b\S+\b/g).length : "0"
// ... versus ...
text.split(/\b\S+\b/).length - 1


First of all, the first expression will crash for a non-empty text without words, for example :!@#$. Because a non-empty text is "true", but the .match will return null, so you'll get a null pointer exception in .length.

Secondly, I suggest a simpler and more intuitive regular expression to match words:

/\w+/g


That is, match a non-empty sequence of word characters.

You could use this as text.match(/\w+/g) (notice the "g" flag) or as text.split(/\w+/). When using match, you need to check if the result is null or not, as you already did.

As for which way is better, using match or split,
I would argue for match:

  • It's more intuitive: it matches the character sequences you're interested in, and then count the occurrences.



  • It's probably more efficient: splitting implies creating an array of the results, but if you only need the size of the array (the count of elements), then it sounds like a waste.

Code Snippets

text ? text.match(/\b\S+\b/g).length : "0"
// ... versus ...
text.split(/\b\S+\b/).length - 1

Context

StackExchange Code Review Q#43274, answer score: 4

Revisions (0)

No revisions yet.