JSFiddle - React, Tailwind, and code Playground

by Chris Buttery

HTML

<div id="border">
    <textarea id='text'></textarea>
</div>
<button id="count">Count</button>
<div id="result">
    Words: <span id="wordCount">0</span><br/>
    Total Characters(including trails): <span id="totalChars">0</span><br/>
    Characters (excluding trails): <span id="charCount">0</span><br/>
    Characters (excluding all spaces): <span id="charCountNoSpace">0</span>
</div>

CSS

#border {
    border: 1px solid red;
    height: 200px;
    width: 100%;
}
textarea {
    height: 100%;
    width: 100%;
    border: 0px;
}

JavaScript

var body = document.body;
var targetEl = body.querySelector('#text');
var trigger = document.querySelector("#count");

var wordCount = body.querySelector('#wordCount');
var totalChars = body.querySelector('#totalChars');
var charCount = body.querySelector('#charCount');
var charCountNoSpace = body.querySelector('#charCountNoSpace');

function resetElements () {
	wordCount.innerHTML = 0;
  totalChars.innerHTML = 0;
  charCount.innerHTML = 0;
  charCountNoSpace.innerHTML = 0;
}

function countWords () {
	var value = targetEl.value;
	console.log('value is ', value, value.length);
  if (!value.length) return resetElements();
  
  var regex = /\s+/gi;
  wordCount.innerHTML = value.trim().replace(regex, ' ').split(' ').length;
  totalChars.innerHTML = value.length;
  charCount.innerHTML = value.trim().length;
  charCountNoSpace.innerHTML = value.replace(regex, '').length;
}

trigger.addEventListener('click', function (e) {
  e.preventDefault();
  countWords();
});

targetEl.addEventListener('keyup', function (e) {
  e.preventDefault();
  countWords();
});