How to Count Words Using JavaScript Or Jquery?

Friends, today I will tell you how many words you have in any sentence and how it can be counted through javascript code, so today I will try to explain you through this tutorial.

Keywords :- Count words with JavaScript, Count Words in a String by JavaScript, How to Count Number of Words with JavaScript or JQuery, How to Count Words in a Sentence by JavaScript Or JQuery

Let me try to explain to you step to step

Step 1:- First you create a page named word-count.html and in this page create an input type textarea using html code and also add an input type button.Then after that create a function named calculate in the input type button.

<!DOCTYPE html>
<html>
<head>
<title>How to Count words Using JavaScript Or Jquery?</title>
</head>
<body>
<h1>How to Count words Using JavaScript Or Jquery?</h1>
<textarea id="input">My super text that does 7 words.</textarea>
<button onclick="calculateword()">Calculate</button>
<span id="count">7</span> words
</body>
</html>

 

Step 2:- Then add the code for counting the sentence in the same page inside the script as shown below.

 

<script>
var calculateword = function() {
var string = document.getElementById('input').value;
var length = string.split(/[^\s]+/).length - 1;
document.getElementById('count').innerHTML = length;
};
</script>

Final Step :- You have to add the script code to count the word of the sentence in the same page as shown in the example below.

word-count.html

<!DOCTYPE html>
<html>
<head>
<title>How to Count words Using JavaScript Or Jquery?</title>
</head>
<body>
<h1>How to Count words Using JavaScript Or Jquery?</h1>
<textarea id="input">My super text that does 7 words.</textarea>
<button onclick="calculateword()">Calculate</button>
<span id="count">7</span> words
<script>
var calculateword = function() {
var string = document.getElementById('input').value;
var length = string.split(/[^\s]+/).length - 1;
document.getElementById('count').innerHTML = length;
};
</script>
</body>
</html>