RxJS Text Counts

Counts letters and words of input or pasted text. Keyup events are the observable stream.

by Lou Mauget

HTML

<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/4.1.0/rx.lite.js"></script>
<h4>Text Counts From an RxJS Stream</h4>
<p>Non-whitespace character count and word counts from text input</p>
<h4>Key or paste text:</h4>

<textarea cols="60" rows="5" autofocus id="txtInput"></textarea>
<p><span id="charCount"></span> <span id="wordCount"></span></p>

CSS

body {
   font-family: "Arial", sans-serif;
 }
 
 #charCount,
 #wordCount {
   font-weidth: 400;
   font-size: 0.95em;
   color: #0000ff;
 }

JavaScript

// #A. DOM elements-of-interest from DOM query selectors
var
  $txtInput = $('#txtInput'),
  $charCount = $('#charCount'),
  $wordCount = $('#wordCount');

// #B. Observable of keyup triggered at textInput -- it's a monad
Rx.Observable.fromEvent($txtInput.get(0), 'keyup')
  .map( function( e ) {
    return {
      cc: (e.target.value.match(/[^\s]/g) || []).length,
      wc: (e.target.value.match(/\b\S+\b/g) || []).length
    }
  })
  // #C. Kick off the stream
  .subscribe( function( v ) {
    console.log(v);
    $charCount.html(` Chars: ${v.cc}`);
    $wordCount.html(` Words: ${v.wc}`);
  });