Word Count Textbox Javascript/php
I am trying to implement a word counter in textbox. I am using the links below: JS Fiddle Second link
Solution 1:
I have make a simple function:
var regex = [/DAV/g, /MAC/g];
functioncountWords() {
var count = [];
regex.forEach(function(reg) {
var m = text.match(reg);
if (m) {
count = count.concat(m);
}
});
// the number of known acronym wrote in the text var acronyms = count.length;
// how much words generated from an acronym (e.g. DAV === 3 words; AB === 2 words and so on)var wordsFromAcronyms = count.join().replace(/,/g,'').length;
// how many words wrote (this is equal to your code)var rawWords = text.match(/\S+/g).length;
// compute the real numberreturn rawWords - acronyms + wordsFromAcronyms;
}
It counts the number of the wrote acronym (the list of the known acronyms is stored in regex
array), then count how much words are generated by the acronyms (wordsFromAcronym
), and then substract the number of acronyms (acronyms
) from the total words (rawWords
) and then add the wordsFromAcronym
.
Here is a PLNKR.
Solution 2:
Try this. I am on my mobile so I cannot make an example easily This will count all words in all uppercase as acronyms
<textareaname="myMessage"onkeyup="wordcount(this.value)"></textarea><inputtype=textid=w_countsize=4readonly><scripttype=""text/javascript"">functionwordcount(message) {
var words = message.split(/\s/);
var cnt = words.length;
for (var i=0;i<cnt;i++) {
if (words[i].length>1 && words[i].match(/^[A-Z]*$/)) cnt += words[i].length-1)
}
var ele = document.getElementById('w_count');
ele.value = cnt;
}
</script>
Post a Comment for "Word Count Textbox Javascript/php"