Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
143
rated 0 times [  147] [ 4]  / answers: 1 / hits: 32499  / 12 Years ago, sun, december 23, 2012, 12:00:00

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?


More From » jquery

 Answers
8



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>




[#81260] Friday, December 21, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
deanna

Total Points: 84
Total Questions: 86
Total Answers: 107

Location: Cyprus
Member since Wed, Dec 8, 2021
3 Years ago
;