I wrote a post a while back discussing how to optimize searching in Flex. I’ve noticed that people keep finding the post by searching for ‘flex string starts with’. The problem is the post doesn’t actually answer that question.
So… here’s how to do it:
public static function startsWith( string:String, pattern:String):Boolean { string = string.toLowerCase(); pattern = pattern.toLowerCase(); return pattern == string.substr( 0, pattern.length ); }
Since we’re talking about string searching I may as well throw out one more quick tip. The above code will match ‘ma’ in ‘Mary’ but let’s say the name is ‘Mary Anne’. Here’s how to match ‘ma’ or ‘an’.
public static function isMatch( string:String, pattern:String ):Boolean { if (startsWith( string, pattern )) { return true; } var words:Array = string.split( " " ); for each (var word:String in words) { if (startsWith( word, pattern )) { return true; } } return false; }
One quick note, in the above code we search the full string first before searching each of the words. We’re doing this to make sure (using the last example of ‘Marry Ane’) that the function also matches ‘mary a’.
Best,
Hillel
What if I want to search only for mary and ane ? and not accept mar or an
Ajo,
In that case you’d simply need to change
if (startsWith( word, pattern ))
to
if (word.toLowerCase() == pattern.toLowerCase())