I need to understand and find a way to replace the occurences of placeholders in a string. I'm working on an app for the Magic, The Gathering tcg game. The text of the card contains a description and some symbols
Let me explain better with an example:
Some possible strings are "{W}{B}, {T}: Prevent all combat damage that would be dealt by target creature this turn." "Flashback {2}{R} (You may cast this card from your graveyard for its flashback cost. Then exile it"
Those strings have to become an html text that Angular can then put inside the DOM. Each of those letters or numbers between curly brackets represent one different symbol to be printed. The possible symbols and the position of those can vary a lot. The text and position because each card is different and the symbol because there are about 1 hundred of possible symbols.
Updates
I've found the solution of:
this._symbolService.symbology.data.forEach((item: CardSymbol) => {
const regEx = new RegExp(item.symbol, 'gm');
const replacement = `<img src="${item.svg_uri}" />`;
this.oracleText = this.oracleText.replace(regEx, replacement);
});
which is almost fine, but it breaks when the symbol string is '{0}' or any other number. Is there any way to tell ts to match the exact string '{0}' (or any other number)?
I hope that I can explain what I need.
CodePudding user response:
{
has a special meaning in Regex, so it needs to be escaped with a backslash. This should do what you want:
this._symbolService.symbology.data.forEach((item: CardSymbol) => {
const regEx = new RegExp('\\' item.symbol, 'gm');
const replacement = `<img src="${item.svg_uri}" />`;
this.oracleText = this.oracleText.replace(regEx, replacement);
});