count words javascript code example

Example 1: javascript count words in string

var str = "your long string with many words.";
var wordCount = str.match(/(\w+)/g).length;
alert(wordCount); //6

//    \w+    between one and unlimited word characters
//    /g     greedy - don't stop after the first match

Example 2: count word and space in text javascript

<html>
<body>
   <script>
      function countWords(str) {
         str = str.replace(/(^\s*)|(\s*$)/gi,"");
         str = str.replace(/[ ]{2,}/gi," ");
         str = str.replace(/\n /,"\n");
         return str.split(' ').length;
      }
      document.write(countWords("   Tutorix is one of the best E-learning   platforms"));
   </script>
</body>
</html>

Example 3: how to check how many strings are in a sentence javascript

function WordCounter (str) {
	var words = str.split(" ").length;
	return words;
}
// this should work!