Function countWords with Regex

by Lucas Silva

JavaScript

function countWords (text){
	text = text.replace(/(< ([^>]+)<)/g, '').replace(/\s+/g, ' ');
  text = text.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
  var wordCount = 0;
  if(text !== ""){
  	wordCount = text.split(" ").length;
  }
  return wordCount;
}

var textao = "Testando o total de palavaras    m    oeoe    ";
var vazio = "          ";
var textinho = "Único";
console.log(countWords(textao));
console.log(countWords(vazio));
console.log(countWords(textinho));