Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations TouchToneTommy on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How do you count the number of instances? 1

Status
Not open for further replies.

glthornton

Programmer
Oct 19, 2005
108
US
Hi,
I'm trying to use Javascript to determine the number of instances of a carot (^) is located within a single string. Here is an example:

Code:
000100^Bombay^MD^Doctor

Once I know the number (3 for the above example), then I'll use the Split command to break them down into an array and then put the pieces back together into another string (with a different format like '000100^Bombay^Doctor^^^').

Can anyone tell me how I may go about doing this?

Kind Regards. Glenn
 
Change the order of doing things:

Code:
var str = "what^ev^er";
var numberOfHats = srt.split("^").length - 1;

Cheers,
Dian
 
How about another one using the match method. Why? Because regexp is so damn sexy! [gorgeous]
Code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "[URL unfurl="true"]http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">[/URL]
<html xmlns="[URL unfurl="true"]http://www.w3.org/1999/xhtml">[/URL]
<head>
<title>title test</title>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
<script type="text/javascript">

var str = "abc^xyz^123^omgwtf";
alert(str.[!]match(/\^/g)[/!].length);

</script>

<style type="text/css"></style>
</head>
<body>
</body>
</html>

-kaht

Lisa, if you don't like your job you don't strike. You just go in every day and do it really half-assed. That's the American way. - Homer Simpson
 
or is it because of SW syndrome?
Don't worry about it [wink]

-kaht

Lisa, if you don't like your job you don't strike. You just go in every day and do it really half-assed. That's the American way. - Homer Simpson
 


This concept may be extended to allow
- a variable character (not just a literal constant value) to be counted
- multiple characters to be counted

I am shaky about RegExp ... and there may be a better way tha eval to make it variable ... so I am open to suggestions.

Here goes:

Code:
<body>
<div id=tracer style="font-family: Courier;">xxx</div>


<script type="text/javascript">



// ************ START of function CountManyChars ****************************


//
//  * CountManyChars *  function 
//
//   FIND OUT HOW MANY (OF 1 or more) SPECIFIC CHARACTERS OCCUR IN A TEXT SRING
//
//      returns array of rows - each containing 2 items
//          1. search characters (chr) and 
//          2. count for all such chr's found in str
//



function CountManyChars(str, chr, mode) {

    // * CountManyChars *


    //    str                 // string of text containing characters to be counted  
    //  

    //    chr                 // string of 1 or more specific search characters 
    //                               - a count of occurrances of each one will be taken

    //    mode                // mode==0 means use simple array split method to count  
    //                        // mode==1 means use Regular Expression match to count

    //   returns an array - each row contains 2 items:  the character and how many times found in str
    //                               - length of chr = size of returned array


    var Karray             = new Array() ;  // returns list of characters and frequency counts
    Karray.length          = 0 ;

    var convtoliteral      = '\\' ;  // constant - part of RegExp string to escape control meaning
    var keychar            = '^'  ;  // workvar - specific character to be counted in str
    var numberOfkeys       = 0    ;  // workvar - count of specific character found in str


    for (i=0;i<chr.length;i++)
     {
  
       keychar        = chr.substring(i,i+1) ;

       if(mode==0)
          {
                numberOfkeys       =   str.split(keychar).length - 1;
          }
       else
          {
             var toliteral  = convtoliteral ;   // use escape sequence for encoded RE characters only
    
             if (   (  (keychar>='0')&&(keychar<='9')  )
                ||  (  (keychar>='a')&&(keychar<='z')  )
                ||  (  (keychar>='A')&&(keychar<='Z')  )
                )
                {
                     toliteral = '' ; 
                }

             REval              = "ONLYkeys = str.match(/"  + toliteral   +  keychar +    "/g)"  ;
             eval(REval);
             if (ONLYkeys==null)  { ONLYkeys = '' ;}
             numberOfkeys       = ONLYkeys.length ;
          }

       Karray[Karray.length] = new Array(keychar,numberOfkeys) ;

    }

   return Karray ;
}



// ************ END of function CountManyChars ******************************






// str is the text with characters to be counted 
// chr is a string - each characters specified here will be counted


//
//  ** Sample Test data **
//


var chr =    "\ \!\"\#\$\%\&\'\("     //  this list of characters to be counted has no duplicates
        +    "\`\-"    
        +    "\)\*\+"
        +    "\,\.\/" 
        +    "0123456789" 
        +    "\:\;\<\=\>\?\@"
        +    "ABCDEFGHIJKLMNOPQRSTUVWXYZ" 
        +    "\[\\\]\^\_"
        +    "abcdefghijklmnopqrstuvwxyz" 
        +    "{|}~" ;


var str =  "abc^xyz^123^omgwtfabcabcabc, four score and seven, e=mc2, liberty equality $1.00" 
        +  "abc^xyz^123^omgwtfac, repeat four score and seven, e=mc2, freedom rights $5.00 ; ( [ 1+1/1*1 ] = 2 ) " 
        +  "waterworld is a wonderful theme park for swans " 
        +  "Dear Sir, Your vile rag of a newspaper clearly demonstates that editors are not human. Signed, A. Friend " 
        +  "The slow yellow dog jumped over the diligent crazy quarrelsome fox." 
        +  "What? peace in our time? Egads - I'm glad or maybe sad. Mutually assured aten~hut! Apply Pie easiness." ;

// ** str=chr ;  // another good sample str ... to count self ... checks for duplicates in search chr pattern







// ***************************************************************************

//
//  ** SAMPLE USE OF FUNCTION **
//
//
//         Produce frequency graph of all listed characters found in string
//

// ***************************************************************************



var Wmode= 0;   //  force array split method


 var Estart0 = new Date();
  
 var Carray             = CountManyChars(str, chr, Wmode) ;
 var Carray             = CountManyChars(str, chr, Wmode) ;
 var Carray             = CountManyChars(str, chr, Wmode) ;
 var Carray             = CountManyChars(str, chr, Wmode) ;
 var Carray             = CountManyChars(str, chr, Wmode) ;
 var Carray             = CountManyChars(str, chr, Wmode) ;
 var Carray             = CountManyChars(str, chr, Wmode) ;
 var Carray             = CountManyChars(str, chr, Wmode) ;
 var Carray             = CountManyChars(str, chr, Wmode) ;
 var Carray             = CountManyChars(str, chr, Wmode) ;
 var Carray             = CountManyChars(str, chr, Wmode) ;
 var Carray             = CountManyChars(str, chr, Wmode) ;
 var Carray             = CountManyChars(str, chr, Wmode) ;
 var Carray             = CountManyChars(str, chr, Wmode) ;
 var Carray             = CountManyChars(str, chr, Wmode) ;
 var Carray             = CountManyChars(str, chr, Wmode) ;
 var Carray             = CountManyChars(str, chr, Wmode) ;
 var Carray             = CountManyChars(str, chr, Wmode) ;
 var Carray             = CountManyChars(str, chr, Wmode) ;
 var Carray             = CountManyChars(str, chr, Wmode) ;
 var Carray             = CountManyChars(str, chr, Wmode) ;
 var Carray             = CountManyChars(str, chr, Wmode) ;
 var Carray             = CountManyChars(str, chr, Wmode) ;
 var Carray             = CountManyChars(str, chr, Wmode) ;
 var Carray             = CountManyChars(str, chr, Wmode) ;
 var Carray             = CountManyChars(str, chr, Wmode) ;

 var Eend0 = new Date();
 var EdurationMS0 = Eend0-Estart0;

 
var Wmode= 1;  // force Regexp match way

 var Estart1 = new Date();
  
 var Carray             = CountManyChars(str, chr, Wmode) ;
 var Carray             = CountManyChars(str, chr, Wmode) ;
 var Carray             = CountManyChars(str, chr, Wmode) ;
 var Carray             = CountManyChars(str, chr, Wmode) ;
 var Carray             = CountManyChars(str, chr, Wmode) ;
 var Carray             = CountManyChars(str, chr, Wmode) ;
 var Carray             = CountManyChars(str, chr, Wmode) ;
 var Carray             = CountManyChars(str, chr, Wmode) ;
 var Carray             = CountManyChars(str, chr, Wmode) ;
 var Carray             = CountManyChars(str, chr, Wmode) ;
 var Carray             = CountManyChars(str, chr, Wmode) ;
 var Carray             = CountManyChars(str, chr, Wmode) ;
 var Carray             = CountManyChars(str, chr, Wmode) ;
 var Carray             = CountManyChars(str, chr, Wmode) ;
 var Carray             = CountManyChars(str, chr, Wmode) ;
 var Carray             = CountManyChars(str, chr, Wmode) ;
 var Carray             = CountManyChars(str, chr, Wmode) ;
 var Carray             = CountManyChars(str, chr, Wmode) ;
 var Carray             = CountManyChars(str, chr, Wmode) ;
 var Carray             = CountManyChars(str, chr, Wmode) ;
 var Carray             = CountManyChars(str, chr, Wmode) ;
 var Carray             = CountManyChars(str, chr, Wmode) ;
 var Carray             = CountManyChars(str, chr, Wmode) ;
 var Carray             = CountManyChars(str, chr, Wmode) ;
 var Carray             = CountManyChars(str, chr, Wmode) ;
 var Carray             = CountManyChars(str, chr, Wmode) ;

 var Eend1 = new Date();
 var EdurationMS1 = Eend1-Estart1;



 var TOTnumberOfkeys    = 0  ;
 var nonhits            = 0  ;
 var MAXnumberOfkeys    = 0  ;

 for (i=0;i<Carray.length;i++)  // * * *  process the captured statistics
 {
       numberOfkeys      = Carray[i][1] ;
       TOTnumberOfkeys   +=   numberOfkeys ; 

       if(numberOfkeys>MAXnumberOfkeys)  
            { 
                 MAXnumberOfkeys = numberOfkeys ; 
            }

       if(numberOfkeys==0)  
             {   
                 nonhits ++ ;
             }
 }



 var breakchars         = '<br>' ;
 var salert             = '<table><tr><td colspan=5>'     ;
 var sl                 =  str.length ;
    salert             += 'Character Frequency of ' 
                       +   chr.length
                       +   ' different characters counted in String length ' 
                       +   (sl) +  breakchars ;

    salert             +='<tr><td colspan=5>' 
                       + ' Time taken (m0: Array split) =' + EdurationMS0 
                       + ' ms. Time taken (m1: RegExp match) =' + EdurationMS1 +' ms.' ;





 var stars = '**************************************************************************************' ;



 for (i=0;i<Carray.length;i++)   //  * * *  produce output * * *
 {

   keychar           = Carray[i][0] ;
   numberOfkeys      = Carray[i][1] ; 

   if(numberOfkeys<1)  {   continue ;    }   // skip if zero occurrances of that char found

   salert            +=  '<tr><td width=20>'   +  keychar.charCodeAt(0)
                      +  '<td width=20>'       +  keychar
                      +  '<td width=20>'       +  (numberOfkeys)  ;

   var showstars = numberOfkeys ;

   if(MAXnumberOfkeys>stars.length)   
       {  
           showstars =  Math.ceil(numberOfkeys 
                     /  (Math.floor(MAXnumberOfkeys/stars.length)) )  ; 
       }

   histogram         =   '<td>'       +  stars.substring(0,showstars) ;

   salert           += histogram +  '</tr>' ;



 }


salert            +=  '<tr><td colspan=5>' + ' Of ' +  (sl)      
                  + ' bytes in string, Characters Counted= '+(TOTnumberOfkeys)  ;

salert            +=  '<tr><td colspan=5>' + ' Of ' 
                  + chr.length 
                  + ' characters listed for counting, Specific Characters Counted= '
                  + (chr.length-nonhits)  ;

tracer.innerHTML  = salert ;

</script>

 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top