how to count words in a sentence javasript though html input code example
Example 1: how to check how many strings are in a sentence javascript
function WordCounter (str) {
var words = str.split(" ").length;
return words;
}
Example 2: 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>