1var str = "your long string with many words.";
2var wordCount = str.match(/(\w+)/g).length;
3alert(wordCount); //6
4
5// \w+ between one and unlimited word characters
6// /g greedy - don't stop after the first match
1<html>
2<body>
3 <script>
4 function countWords(str) {
5 str = str.replace(/(^\s*)|(\s*$)/gi,"");
6 str = str.replace(/[ ]{2,}/gi," ");
7 str = str.replace(/\n /,"\n");
8 return str.split(' ').length;
9 }
10 document.write(countWords(" Tutorix is one of the best E-learning platforms"));
11 </script>
12</body>
13</html>
1var input = document.getElementById('typed-text');
2
3input.onkeydown = function (e) {
4
5 if (e.keyCode === 13) {
6
7 var paragraph = document.getElementById('paragraph');
8 var result = document.querySelector('.result-output');
9 var regexp = new RegExp(this.value, 'g');
10 var textIncludes = paragraph.textContent.match(regexp);
11
12 if (result)
13 result.remove();
14
15 paragraph.innerHTML = paragraph.textContent.replace(
16 regexp,
17 '<span style="color:red">' + this.value + '</span>');
18
19 paragraph.insertAdjacentHTML(
20 'afterend',
21 '<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>');
22
23 }
24
25}
26<div id="highlights">
27 <div class="container">
28 <div class="row">
29 <div class="col-md-12" id="paragraph">
30 <p>
31 text
32 </p>
33 </div>
34 <div class="col-md-12 input-group mt-3">
35 <div class="input-group-prepend">
36 <span class="input-group-text" id="basic-addon1">
37 <i class="fas fa-pencil-alt"></i>
38 </span>
39 </div>
40 <input id="typed-text" type="text" class="form-control" placeholder="Type text">
41 </div>
42 </div>
43 </div>
44 </div>
45