I’m working on a training simulator that allows people to virtually highlight text (like in iBooks) in a textField. I’ll probably post the code for the highlighting portion when the project is done.

For now, I thought I’d post this simple AS3 utility function I wrote, which allows you to find all instances of string inside another string. It accepts two arguments:

  • searchFor:String – string you wish to search FOR
  • searchIn:String – string you wish to search IN
  • caseSensitive:Boolean=true – (optional) determines whether comparisons are case sensitive

It will return an array containing the indices at which searchFor is found in searchIn. You can check the length of the array returned to get the number of times the search string appears in the search text. If the length is 0, searchFor does not appear in searchIn.

package com.baconandgames.utils{
public class Strings{
 
// returns an array of indexes for each occurance of searchFor in searchString
// var s:String = "Haw many cats are in this sentence about cats?";
// Strings.findAllStringsInString("cats",s); // returns [9,41];
 
public static function findAllStringsInString(searchFor:String,searchIn:String,caseSensitive:Boolean=true):Array{   
  if(!caseSensitive){             
    searchFor = searchFor.toLocaleLowerCase();        
    searchIn = searchIn.toLocaleLowerCase();   
  }       
  var a:Array = new Array();       
  var i:int = -1;     
  while ((i = searchIn.indexOf(searchFor, i+1)) != -1) a.push(i);      
  return a;
}
}

*simplified with suggestions by my good buddy and web-ninja Rob Colburn