Welcome Guest [Log In] [Register]
This board has been archived and is no longer accepting new questions. If you have a support question for your ZetaBoard, please visit us at the new support board. Registration is free and easy.


Visit the NEW ZetaBoards Support forum!

Username:   Password:
Add Reply
Word Count Function
Topic Started: Mar 31 2008, 01:21 PM (582 Views)
Viral
Member Avatar
i'm stanley nao
[ *  *  *  *  * ]
When looking back at codes, when needing to work out how many words there were in a string, I would use something like:
Code: HTML
 
str.split(" ").length


I was just a bit bored and tried working on a better version, which is shown underneath here. Is there anything I would need to change? While typing this, I just thought of a much easier way, using RegExp, but I'll try that out later.

Code: HTML
 
function word_count(str,num){
limited=["`","¬","¦","!","\"","£","$","%","^","&","\*","\(","\)","-","_","+","=","{","}","[","]","@","\'","~","#",":",";","\\","|",",","<",".",">","?","/","0","1","2","3","4","5","6","7","8","9"];
for(i=0;i<limited.length;i++){str=str.split(limited[i]).join("");}
if(isNaN(num) || num==0){return str.split(" ").length;}
else if(num==1){words=[];
for(w=0;w<str.split(" ").length;w++){
words[w]=str.split(" ")[w];
}}return words;}


That's the function. Using RegExp, I wouldn't need the limited array, just use the non word pattern (if I can remember what that is).

So if I were to use:

[/i]
Code: HTML
 
var str="omg hello432 I$% am Vir al";
alert(word_count(str,1)[2]);


It would alert I.

Any comments?
Edited by Viral, Mar 31 2008, 01:21 PM.
Offline Profile Quote Post Goto Top
 
1 user reading this topic (1 Guest and 0 Anonymous)
« Previous Topic · Coding & Modifications · Next Topic »
Add Reply