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

by Peter deHaan on September 8, 2007

in StringUtil

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.

{ 6 comments… read them below or add one }

1 FlexLover September 8, 2007 at 10:40 am

Tank’you an other one very useful example!

Reply

2 whataslacker May 31, 2008 at 10:18 pm

this would make for a great ‘mad libs’ program

Reply

3 Santosh Kulkarni December 24, 2008 at 2:19 am

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

Reply

4 Peter deHaan December 26, 2008 at 1:49 pm

Santosh Kulkarni,

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

Peter

Reply

5 Santosh Kulkarni January 6, 2009 at 4:40 am

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;
    }

Reply

6 Reny Mohan January 20, 2010 at 5:41 am

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

Reply

Leave a Comment

Sorry, this blog is terrible at eating HTML comments.
If you're pasting any HTML/XML/MXML code, you need to convert your < characters to &lt; and your > characters to &gt; .

You can 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

Previous post:

Next post: