sorry i'm very new to JS, i'm trying to write some code to dynamically count the words on a page, this code is within a 'whenkeydown' function:
var text = $(this).val();
var word=text.split(" ")
//word counter
function countWords(word, text) {
var y = word.value;
var words = 0;
a = y.replace(/\s/g, ' ');
a = a.split(' ');
for ( z = 0; z < a.length; z++) {
if (a[z].length > 0)
words++;
}
wordCount = words;
}
But i get an error message saying "TypeError: y is undefined" in the debugger? Thanks
word
is an array, it does not have attribute value
. Moreover your functions seems to accept the whole string as a parameter, not an array of words. Here is a clearer version:
function countWords(text) {
var words = text.replace(/\s/g, ' ').split(' ');
var wordCount = 0;
for (var z = 0; z < words.length; z++) {
if (words[z].length > 0)
wordCount++;
}
return wordCount;
}
var text = $(this).val();
var wordCount = countWords(text);
function countWords(wordsArray) {
var words = 0;
try{
for(k in wordsArray){
var sa = (wordsArray[k] ? word.value.replace(/\s/g, ' ') : '').split(' ');
for (i in sa) if(sa[i].trim()) words++;
}
catch(ex){}
return words;
}
OR:
$(this).val().match(/\S+/g).length;