Word count tool

A simple client-side tool to count the number of words in a text.

Author
Published

June 30, 2024

Most posts under miscellaneous are for personal purposes. But if you find this useful, that’s great!

Often, I stumble upon the requirement to count the number of words in a text. There are some online tools for this, but they often do fancy stuff, send your text to servers or generally not very privacy-friendly. This is a simple tool that runs in the browser using Observable JS. To look at the code that runs this, expand the “code” blocks.

Enter your text in the input field below, and the tool will count the number of characters, words, sentences, and paragraphs in the text.

Code
viewof inputString = Inputs.textarea({placeholder: "Enter your text here...", rows: 10})
Code
// Produce the HTML as a table with lines and some padding between each column 
html`Counts:
<div><table style="border-collapse: collapse; margin-top: 10px;">
    <tr>
        <td style="padding: 5px; border: 1px solid black;"><b>Characters</b></td>
        <td style="padding: 5px; border: 1px solid black;"><b>Words</b></td>
        <td style="padding: 5px; border: 1px solid black;"><b>Sentences</b></td>
        <td style="padding: 5px; border: 1px solid black;"><b>Paragraphs</b></td>
    </tr>
    <tr>
        <td style="padding: 5px; border: 1px solid black;">${charCount}</td>
        <td style="padding: 5px; border: 1px solid black;">${wordCount}</td>
        <td style="padding: 5px; border: 1px solid black;">${sentenceCount}</td>
        <td style="padding: 5px; border: 1px solid black;">${paragraphCount}</td>
    </tr>
</table></div>`
Code
charCount = inputString.length

// Count words
wordCountMatch = inputString.match(/\b[-?(\w+)?']+\b/gi)
wordCount = wordCountMatch !== null ? wordCountMatch.length : 0

// Count sentences
sentenceCountMatch = inputString.match(/[.!?]+/g)
sentenceCount = sentenceCountMatch !== null ? sentenceCountMatch.length : 0

// Count paragraphs
paragraphCountPre = inputString.replace(/\n$/gm, '').split(/\n/).length
paragraphCount = wordCountMatch !== null ? paragraphCountPre : 0

Reuse

https://creativecommons.org/publicdomain/zero/1.0/