With the below code, when we enter some text in an textbox and click button, we will get the count of words and characters in the text entered.
- <input type="text" id="txtinput" />
- <button onclick="countwords()">
- Check Count</button>
- <script>
- function countwords() {
- var val = document.getElementById("txtinput").value;
- var words = 0, chars = 0;
- if (val != "") {
- words = val.replace(/\s+/gi, ' ').split(' ').length;
- chars = val.length;
- }
- alert(chars + " Characters & " + words + " Words!");
- }
- </script>