how to count the number of words in a string in 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);
Example 2: string methods javascript count number of words inside a string
<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: 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 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>