Please login or register. Welcome to the Studio, guest!


Quick Links:


newBookmarkLockedFalling

Moose

Moose Avatar

****
Senior Member

449


August 2005
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. :P
Chris 3.0 [New features? Yes.] says:
:P
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:
:P Yeah, I'll get right on that... right after I learn to fly.

Aaron

Aaron Avatar
Bad Wolf

****
Dedicated Studio Member

859


November 2006
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)
}

Chris

Chris Avatar

******
Head Coder

19,519


June 2005
var wordreg = /\b[\w\d]+\b/gi;

That's the RegExp I wrote for a code a while ago. :P Works fine too.

newBookmarkLockedFalling