Count Words and Characters [closed]
I've been looking to add a word and character count to a textarea using jQuery although all I've found are plugins to limit characters and words.
I would like to update in real-time, so that every time a user adds a character, or a word, the counter updates.
Is there a simple way to check for words and characters?
function wordCount(val) {
var wom = val.match(/\S+/g);
return {
charactersNoSpaces: val.replace(/\s+/g, '').length,
characters: val.length,
words: wom ? wom.length : 0,
lines: val.split(/\r*\n/).length
};
}
var textarea = document.getElementById('text');
var result = document.getElementById('result');
textarea.addEventListener('input', function() {
var wc = wordCount(this.value);
result.innerHTML = (`
<br>Characters (no spaces): ${wc.charactersNoSpaces}
<br>Characters (and spaces): ${wc.characters}
<br>Words: ${wc.words}
<br>Lines: ${wc.lines}
`);
});
<textarea id="text" cols="30" rows="4"></textarea>
<div id="result"></div>
char_count = $("#myTextArea").val().length;
word_count = $("#myTextArea").val().split(" ").length;