A Flash Developer Resource Site

Results 1 to 2 of 2

Thread: Count number of times a letter appears in a string and display number in real time?

  1. #1
    Junior Member
    Join Date
    Mar 2013
    Posts
    2

    Question Count number of times a letter appears in a string and display number in real time?

    Hello,

    I need to count how many times a letter is contained inside a string as the user types in the textbox (i.e., in real time) and display the count on the page? I would really appreciate it if someone can give me some guidance how to do that in ActionScript 3.0/Flash CS6.

    Thanks a lot in advance!

  2. #2
    Total Universe Mod jAQUAN's Avatar
    Join Date
    Jul 2000
    Location
    Honolulu
    Posts
    2,429
    Using the Event.CHANGE event listener, you can get notified every time the contents of a text field changes (ie. the user typed or deleted characters)
    Code:
    myTextField.addEventListener(Event.CHANGE, onTextChange);
    Then you'll have to use String.match() to find the number of occurrences. But to count them all, you have to pass a Regular Expression to match(). Regular Expression are basically string voodoo which are fairly difficult to understand but can do amazing things. In your case a simple character match is not too difficult.

    Code:
    function onTextChange(event:Event):void{
      // here you can do the counting
      // first we create the expression to match.
      // The single forward slashes '/' mean "this is the beginning and end of my expression".
      // The 'g' on the end is a modifier that tells it we want a global match meaning "find all the matches in this string"
      // the open and close brackets '[]' means "here is a list of things to look for". In this example we are searching or any lower case or upper case 'S'
      // the pipe between the two s's means match a lower case OR an upper case.
      var pattern:RegExp = /[s|S]/g;
      // now we call match() on the users input and pass in the RegExp.
      // it returns an array of all matches so the length of that array is your number.
      var results:Array = myTextField.text.match(pattern);
      trace ("There are:", results.length, "S's in the text field"); // If the users in put was "See Spot Run" this would trace: "There are 2 S's in the text field"
    }

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  




Click Here to Expand Forum to Full Width

HTML5 Development Center