Skip to content

Commit d617d1e

Browse files
committed
Added substitute method - fix for issue mikechambers#164 on original fork
1 parent fa7507f commit d617d1e

File tree

2 files changed

+38
-2
lines changed

2 files changed

+38
-2
lines changed

src/com/adobe/utils/StringUtil.as

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -235,5 +235,34 @@ package com.adobe.utils
235235
//todo: this needs a unit test
236236
return (s != null && s.length > 0);
237237
}
238+
239+
/**
240+
* Variable string injection. Replaces all instances of '{n}' with
241+
* the parameter equivalent where 'n' equals a number.
242+
*
243+
* @param string The first string to injects variables into.
244+
*
245+
* @param ... The unlimited number of variables to be injected.
246+
*
247+
* @returns A string with the variables injected
248+
*
249+
* @langversion ActionScript 3.0
250+
* @playerversion Flash 9.0
251+
* @tiptext
252+
*/
253+
public static function substitute(string:String, ...params:Array):String
254+
{
255+
// Check to see if there's something to inject
256+
if(params && params.length > 0)
257+
{
258+
// Iterate through array, try to inject vars in string
259+
for(var i:uint = 0, len:uint = params.length; i<len; i++)
260+
{
261+
string = replace(string, '{' + i + '}', params[i].toString());
262+
}
263+
}
264+
265+
return string;
266+
}
238267
}
239268
}

tests/src/com/adobe/utils/StringUtilTest.as

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -32,10 +32,10 @@
3232

3333
package com.adobe.utils
3434
{
35+
import com.adobe.utils.StringUtil;
36+
3537
import flexunit.framework.TestCase;
3638
import flexunit.framework.TestSuite;
37-
38-
import com.adobe.utils.StringUtil;
3939

4040
public class StringUtilTest extends TestCase
4141
{
@@ -306,5 +306,12 @@ package com.adobe.utils
306306
assertFalse("StringUtil.stringHasValue(\"\") == false", StringUtil.stringHasValue(""));
307307
assertTrue("StringUtil.stringHasValue(\"XXX\") == true", StringUtil.stringHasValue("XXX"));
308308
}
309+
310+
public function testSubstitute():void {
311+
assertEquals(StringUtil.substitute("", 1, 2, 3), "");
312+
assertEquals(StringUtil.substitute("none"), "none");
313+
assertEquals(StringUtil.substitute("none", 1, 2, 3), "none");
314+
assertEquals(StringUtil.substitute("This {0} {1} {2} string.", "is", "a", "test"), "This is a test string.");
315+
}
309316
}
310317
}

0 commit comments

Comments
 (0)