var strToBeReplace:String= "Hi! I am {0}, and I like {1}, I used to be a {2}"; // many {\d} like curly brace to be replace
trace(replaceCurlyBrace(strToBeReplace, "tom", "eating", "techer"));
// expect output: Hi! I am tom, and I like eating, I used to be a teacher
function replaceCurlyBrace(str:String, ... args):void
{
// ... how to implement
}
I had tried this:
var str:String = "bla bla {0} bla";
var reg:Regexp = new Regexp("{0}");
trace(strToBeReplace.replace(reg,"tim"));
// real output : bla bla {0} bla
but it did't work.
I had tried double slash style regexp : /{0}/, but ide complains syntax error.
Let's start by what you have tried :
var reg:RegExp = new RegExp('{0}'); // you can write it : var reg:RegExp = /{0}/;
var str:String = 'bla bla {0} bla';
trace(str.replace(reg, 'tim'));
Here you should know that {}
is a quantifier metacharacter
which is used to specify a numeric quantifier or quantifier range for a previous item, so for example, if you write /a{3}/
you tell
the compiler that you are looking for any 'aaa' string, so in reality writing /{0}/
doesn't have any sens or utility.
So to indicate to the compiler that you are looking for the string "{0}"
, you can do like this :
var reg:RegExp = /{[0]}/; // you can write it : var reg:RegExp = new RegExp('{[0]}');
OR, you can escape the {}
using a single \
( \\
if using a string ) :
var reg:RegExp = /\{0}/; // you can write it : var reg:RegExp = new RegExp('\\{0}');
Which give you this code :
var reg:RegExp = new RegExp('\\{0}');
var str:String = 'bla bla {0} bla';
trace(str.replace(reg, 'tim')); // gives : bla bla tim bla
Returning to your question, you have n
words to replace within your string, so you can do like this :
var str:String = 'Welcome to {0}, the free {1} that {2} can {3}.';
str = replaceCurlyBrace(str, 'Wikipedia', 'encyclopedia', 'anyone', 'edit');
trace(str); // gives : Welcome to Wikipedia, the free encyclopedia that anyone can edit.
function replaceCurlyBrace(str:String, ... args): String {
var exp0:RegExp = /\{/, // or : /{[/
exp1:RegExp = /}/, // or : /]}/
regex:RegExp;
// if we have words
if(args.length > 0) {
for(var i:int = 0; i<args.length; i++){
// you can also write it : regex = new RegExp('\\{' + i + '}');
// or regex = new RegExp('{[' + i + ']}');
regex = new RegExp(exp0.source + i + exp1.source);
str = str.replace(regex, args[i]);
}
}
return str;
}
For more details about RegExp
, you can take a look on :
Hope that can help.