I have a piece of code which replaces tokens in a string. I have the replacement values stored in an array.
Essentially, I would like to analyse the string and replace it by array key. For example, I want to replace any instance of [my_forename] with replacements['my_forname']. The keys in the array are identical to whatever is between the squared brackets in the string.
A more comprehensive view:
replacements['my_forename'] = 'Ben';
replacements['my_surname'] = 'Major';
replacements['my_verbose_name'] = 'Ben Major';
// The following is the input string:
// 'My name is [my_forename] [my_surname], or [my_verbose_name].';
// And it should output:
// 'My name is Ben Major, or Ben Major.';
If anyone can offer a RegEx that will handle the replacement, I would be grateful. It is possible that there will be more than one instance of the same token, but I have handled that using the following replaceAll function:
String.prototype.replaceAll = function(needle, replacement)
{
return this.replace(new RegExp(needle, 'g'), replacement);
}
This causes a max stack limit though, because creating a RegExp object from anything containing [] causes issues.
Any help would be gratefully received!