word count in javascript code example

Example 1: word count algorithm javascript

function getWordCount() {  let map = {};for (let i = 0; i < array.length; i++) {    let item = array[i];    map[item] = (map[item] + 1) || 1;  }  return map;}getWordCount(array); // { apple: 3, orange: 2 }

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!

Example 4: javascript Document word search and count

var input = document.getElementById('typed-text');

input.onkeydown = function (e) {

    if (e.keyCode === 13) {

        var paragraph = document.getElementById('paragraph');
        var result = document.querySelector('.result-output');
        var regexp = new RegExp(this.value, 'g');
        var textIncludes = paragraph.textContent.match(regexp);
            
        if (result)
            result.remove();

        paragraph.innerHTML = paragraph.textContent.replace(
            regexp,
            '<span style="color:red">' + this.value + '</span>');

        paragraph.insertAdjacentHTML(
            'afterend',
            '<span class="result-output" style="display: block; padding: 5px; margin-top: 10px; background: #eee; color: green;">' + (textIncludes ? textIncludes.length : 0) + ' words has been found.</span>');
            
    }

}
<div id="highlights">
        <div class="container">
            <div class="row">
                <div class="col-md-12" id="paragraph">
                    <p>
                       text
                    </p>
                </div>
                <div class="col-md-12 input-group mt-3">
                    <div class="input-group-prepend">
                        <span class="input-group-text" id="basic-addon1">
                            <i class="fas fa-pencil-alt"></i>
                        </span>
                    </div>
                    <input id="typed-text" type="text" class="form-control" placeholder="Type text">
                </div>
            </div>
        </div>
    </div>

Tags:

Php Example