Flex Tip: Check if string starts with…

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’.


Tags: , ,

2 responses to “Flex Tip: Check if string starts with…”

  1. Ajo Paul says :

    What if I want to search only for mary and ane ? and not accept mar or an

    • Hillel says :


      In that case you’d simply need to change
      if (startsWith( word, pattern ))
      if (word.toLowerCase() == pattern.toLowerCase())

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: