|
Once again, I don't know if a function or method has been already created for this. Anyway, this count the number of words in a string. It's pretty simple. function countWords(wordStr){ var wordsStr = wordStr.toString(); if(wordsStr.match(/^\s+$/)){ var wordCount = 0; return wordCount; } var wordCount = 1; wordsStr = wordsStr.replace(/^\s+/,''); wordsStr = wordsStr.replace(/\s+$/,''); while(wordsStr.match(/(\s+)/)){ wordCount++; wordsStr = wordsStr.replace(RegExp.$1,''); } return wordCount; } For example this should alert the number 5: <script type="text/javascript"> <!-- function countWords(wordStr){ var wordsStr = wordStr.toString(); if(wordsStr.match(/^\s+$/)){ var wordCount = 0; return wordCount; } var wordCount = 1; wordsStr = wordsStr.replace(/^\s+/,''); wordsStr = wordsStr.replace(/\s+$/,''); while(wordsStr.match(/(\s+)/)){ wordCount++; wordsStr = wordsStr.replace(RegExp.$1,''); } return wordCount; } alert(countWords("Joe is nice and cool")); //--> </script>
Last Edit: Feb 24, 2007 13:14:05 GMT by Moose
|
Greg says: Coding music... Greg says: Hmm... Greg says: I wouldn't rule it out. Chris 3.0 [New features? Yes.] says:
Greg says: If you think about machine code it's a bunch of 1s and 0s Chris 3.0 [New features? Yes.] says: Anything is possible. Greg says: Yeah try to code Metallica Chris 3.0 [New features? Yes.] says: Yeah, I'll get right on that... right after I learn to fly.
|
|
|
|
I'm a bit rusty with my RegExp but this should work fine too,
String.prototype.count = function() { return (this.match(/\b/g).length / 2) }
|
|
|
|
var wordreg = /\b[\w\d]+\b/gi; That's the RegExp I wrote for a code a while ago. Works fine too.
|
|
|
|