Substituting values in strings using the Flex StringUtil class’s substitute() method
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!
<?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.
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.
-
Add Widgets (Content Sidebar)
This is your Content Sidebar. Edit this content that appears here in the widgets panel by adding or removing widgets in the Content Sidebar area.
6 Responses to Substituting values in strings using the Flex StringUtil class’s substitute() method
Leave a Reply Cancel reply
-
Categories
- Accordion
- AccordionHeader
- ActionScript
- AddChild
- AdvancedDataGrid
- Alert
- alpha
- Animate
- AnimateProperties
- Application
- Application (Spark)
- ArrayCollection
- BarChart
- baseColor
- beta
- beta1
- beta2
- Bitmap
- Bitmap/BitmapData
- BitmapData
- BitmapFill
- BitmapFill (Spark)
- BitmapGraphic
- BitmapImage
- BitmapImage (Spark)
- BitmapImageResizeMode
- Border (Spark)
- BorderContainer (Spark)
- Box
- BuildInfo
- Button
- Button (Spark)
- ButtonBar
- ButtonBar (Spark)
- ByteArray
- Camera
- Charting
- CheckBox
- CheckBox (Spark)
- ClassFactory
- CollectionEvent
- Color
- ColorPicker
- ColorUtil
- ComboBox
- ComboBoxArrowSkin
- Compiler
- Component
- Component (Spark)
- Configuration
- Container
- ContextMenu
- ContextMenuEvent
- ContextMenuItem
- CSSCondition
- CSSSelector
- CSSStyleDeclaration
- CurrencyFormatter
- CursorManager
- Data Binding
- DataGrid
- DataGrid (Spark)
- DataGridColumn
- Date
- DateBase
- DateChooser
- DateField
- DateFormatter
- Debugging
- DefaultComplexItemRenderer
- DefaultTileListEffect
- DropDownList
- DropDownList (Spark)
- DropDownListButtonSkin
- DropDownListSkin
- DropShadowFilter
- E4X
- Effects
- Ellipse
- EmailValidator
- Embed
- Event
- Fade
- FileFilter
- FileReference
- fill
- Filters
- Flash
- Flash Integration
- FlashVars
- Flex 3 SDK
- Flex Builder
- Flex Builder 3
- Flex SDK
- Flex4
- FLVPlayback
- FocusManager
- FontLookup
- Fonts
- Form
- Form (Spark)
- FormHeading (Spark)
- FormItem
- FormItem (Spark)
- Forms
- FTETextField (Spark)
- FullScreen
- FullScreenEvent
- FxAnimateColor
- FxButtonBar
- FxCheckBox
- FXG
- FxHScrollBar
- FxHSlider
- FxList
- FxNumericStepper
- FxRadioButton
- FxRotate3D
- FxScroller
- FxTextArea
- FxTextInput
- FxToggleButton
- FxVScrollBar
- FxVSlider
- getStyleDeclaration()
- GradientEntry
- Graphic (Spark)
- HBox
- HDividedBox
- HGroup (Spark)
- HorizontalLayout
- HorizontalList
- HSBColor (Spark)
- HScrollBar (Spark)
- HSlider
- HSlider (Spark)
- HTML template
- ID3Info
- Image
- Image (Spark)
- ImageSnapshot
- itemRenderer
- JointStyle
- Label
- Label (Spark)
- Legend
- LegendItem
- LigatureLevel
- Line
- LinearGradientStroke
- LineScaleMode
- LinkBar
- LinkButton
- List
- List (Spark)
- Menu
- MenuBar
- Metadata
- MetadataEvent
- Model
- Mouse
- MouseCursor
- MouseEvent
- Move
- Namespace
- NavigatorContent (Spark)
- needsSWF
- NetConnection
- NetStream
- Nightly Builds
- NumberBaseRoundType
- NumberFormatter
- NumberValidator
- NumericCompare
- NumericStepper
- NumericStepper (Spark)
- ObjectProxy
- ObjectUtil
- paddingLeft
- paddingRight
- Panel
- Panel (Spark)
- Parallel
- Path
- PieChart
- PieSeries
- PieSeriesItem
- PopUpAnchor (Spark)
- PopUpButton
- PopUpManager
- ProgrammaticSkin
- ProgressBar
- PropertyChangeEvent
- QName
- RadialGradient
- RadioButton
- RadioButton (Spark)
- RadioButtonGroup
- RadioButtonGroup (Spark)
- Rect
- RegExp
- Regular Expressions
- Repeater
- RichEditableText
- RichText
- RichText (Spark)
- RichTextEditor
- Rotate
- Rotate3D (Spark)
- Scroller (Spark)
- Sequence
- setStyle()
- SimpleText
- SimpleText (Spark)
- skinClass
- Slider
- SliderEvent
- SolidColor
- SolidColorStroke
- Sort
- SortField
- Sound
- SoundEffect
- Spinner (Spark)
- SpriteVisualElement (Spark)
- StageDisplayState
- States
- StringUtil
- StringValidator
- StyleManager
- Styles
- SWFLoader
- SWFObject
- System
- SystemManager
- TabBar
- TabBar (Spark)
- TabNavigator
- TabStopFormat
- Text
- Text Layout Framework (TLF)
- TextArea
- TextArea (Spark)
- TextBox
- TextConverter
- TextEvent
- TextFlow
- TextFlowUtil
- TextFormat
- TextGraphic
- TextInput
- TextInput (Spark)
- TextLayoutFormat
- TextView
- Themes
- TileLayout
- TileList
- TileOrientation
- Timer
- TitleWindow
- TitleWindow (Spark)
- TLF
- ToggleButton (Spark)
- ToggleButtonBar
- ToolTip
- Transition
- Tree
- TruncationOptions
- UIComponent
- UIFTETextField
- Updater
- URLLoader
- URLRequest
- URLUtil
- URLVariables
- ValidationResultEvent
- Validator
- Validators
- VBox
- VDividedBox
- Vector
- VerticalLayout
- VerticalLayout (Spark)
- VGroup (Spark)
- Video
- VideoDisplay
- VideoElement
- VideoElement (Spark)
- VideoEvent
- VideoPlayer (Spark)
- VideoPlayerScrubBar
- ViewStack
- VScrollBar (Spark)
- VSlider
- VSlider (Spark)
- XML
- XMLList
- XMLListCollection
- ZipCodeValidator
- ZipCodeValidatorDomainType
- Zoom
-
Articles
- December 2010
- November 2010
- October 2010
- September 2010
- August 2010
- July 2010
- June 2010
- May 2010
- April 2010
- March 2010
- February 2010
- January 2010
- December 2009
- November 2009
- October 2009
- September 2009
- August 2009
- July 2009
- June 2009
- May 2009
- April 2009
- March 2009
- February 2009
- January 2009
- December 2008
- November 2008
- October 2008
- September 2008
- August 2008
- July 2008
- June 2008
- May 2008
- April 2008
- March 2008
- February 2008
- January 2008
- December 2007
- November 2007
- October 2007
- September 2007
- August 2007
- July 2007
-
Meta


Tank’you an other one very useful example!
this would make for a great ‘mad libs’ program
StringUtil.substitute It seems that it will not work with Special charchacters like $ specially with $$ it will omit one $.
Santosh Kulkarni,
Can you please file a bug at http://bugs.adobe.com/flex/ and include a simple test case, if possible.
Peter
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; }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