The following example shows how you can substitute values in a string with specified values using the static StringUtil.substitute() method in Flex. Similar to the printf() and sprintf() methods in other languages.

Full code after the jump.

Before getting right to the awkward example, lets look at the method signature from the documentation: “Flex 3 Language Reference : StringUtil.substitute()“.

public static function substitute(str:String, ... rest):String {...}

As we can see, this method takes a variable number of parameters (the “… rest” part), with the first parameter being a String object. This string can contain special placeholders such as {0} and {1} which will map to the additional parameters supplied to the method in the ... rest bit there.

Since a code snippet is worth a 1000 words, here’s a super simple example:

var result:String = StringUtil.substitute("The {0} brown {1}", "quick", "fox");
trace(result); // The quick brown fox

So, the {0} in the str parameter gets replaced by “quick” (the first item in the ... rest parameter) and likewise the {1} gets replaced by “fox”.

Hopefully that made a bit of sense, onward to my awkward example which lets you generate fun form letters!

View MXML

<?xml version="1.0" encoding="utf-8"?>
<!-- http://blog.flexexamples.com/2007/09/08/substituting-values-in-strings-using-the-flex-stringutil-classs-substitute-method/ -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
        layout="vertical"
        verticalAlign="middle"
        backgroundColor="white">

    <mx:Script>
        <![CDATA[
            import mx.utils.StringUtil;

            private function button_click(evt:MouseEvent):void {
                textArea.text = StringUtil.substitute(template,
                                    var0.text,
                                    var1.text,
                                    var2.text,
                                    var3.text,
                                    var4.text,
                                    var5.text);
            }
        ]]>
    </mx:Script>

    <mx:String id="template" source="template.txt" />

    <mx:HBox width="100%">
        <mx:Form>
            <mx:FormItem label="0:">
                <mx:TextInput id="var0" text="John Doe" />
            </mx:FormItem>
            <mx:FormItem label="1:">
                <mx:TextInput id="var1" text="death" />
            </mx:FormItem>
            <mx:FormItem label="2:">
                <mx:TextInput id="var2" text="Mega Insurance Inc." />
            </mx:FormItem>
            <mx:FormItem label="3:">
                <mx:TextInput id="var3" text="policy" />
            </mx:FormItem>
            <mx:FormItem label="4:">
                <mx:TextInput id="var4" text="terminated" />
            </mx:FormItem>
            <mx:FormItem label="5:">
                <mx:TextInput id="var5" text="serve you" />
            </mx:FormItem>
            <mx:FormItem direction="horizontal">
                <mx:Button id="button"
                        label="Substitute"
                        click="button_click(event)" />
                <mx:Button label="Reset"
                        click="textArea.text = template;" />
            </mx:FormItem>
        </mx:Form>
        <mx:TextArea id="textArea"
                text="{template}"
                editable="false"
                width="100%"
                height="100%" />
    </mx:HBox>

</mx:Application>

View source is enabled in the following example.

 
Tagged with:
 
About The Author

Peter deHaan

Peter deHaan currently works for Adobe on the Flex SDK QA team. While not working on Flex, Flash, and ColdFusion applications, Peter enjoys making up bios and writing in 3rd person. Peter's rarely updated blog can be found at blogs.adobe.com/pdehaan/, actionscriptexamples.com, airexamples.com, and coldfusionexamples.com.

6 Responses to Substituting values in strings using the Flex StringUtil class’s substitute() method

  1. FlexLover says:

    Tank’you an other one very useful example!

  2. whataslacker says:

    this would make for a great ‘mad libs’ program

  3. Santosh Kulkarni says:

    StringUtil.substitute It seems that it will not work with Special charchacters like $ specially with $$ it will omit one $.

  4. Peter deHaan says:

    Santosh Kulkarni,

    Can you please file a bug at http://bugs.adobe.com/flex/ and include a simple test case, if possible.

    Peter

  5. Santosh Kulkarni says:

    The work around for the above problem would be having custom Implementaion of

    stringUtil.substitute (str:String, … rest):String {} as below. By just avoding using regExp. Because in RegExp “$” is used as the metacharcter so it has got Special meaning.

    public static function substitute1(str:String, ... rest):String
        {
            if (str == null) return '';
    
            // Replace all of the parameters in the msg string.
            var len:uint = rest.length;
            var args:Array;
            if (len == 1 && rest[0] is Array)
            {
                args = rest[0] as Array;
                len = args.length;
            }
            else
            {
                args = rest;
            }
    
            for (var i:int = 0; i < len; i++)
            {
                str = str.replace("{"+i+"}", args[i]);
            }
    
            return str;
        }
    
  6. Reny Mohan says:

    Hi peter,
    i’m struggling with flex printing. i searched a lot in the net ..i want to print a part of the display screen.pls help me..
    thanks in advance
    Reny

Leave a Reply

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="">

Anti-Spam Protection by WP-SpamFree