1

I have texts coming from the database that need to be modified before displaying them.

E.g. as seen below, in the code block, a text can have one or multiple {variables} that need to be replaced by html <i> tag with a class name that comes from the variable.

const string = 'Lorem ipsum dolor sit {icon_exit} consectetur {icon_plus} elit.';

const matched = string.match(/{(.*?)}/g); //["{icon_exit}", "{icon_plus}"]

//... replace both with `<i class="icon-${exit or plus}"></i>`

return string; //Lorem ipsum dolor sit <i class="icon-exit"></i> consectetur <i class="icon-plus"></i> elit.
Berisko
  • 545
  • 2
  • 8
  • 21
  • [`replace`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace#specifying_a_function_as_a_parameter) can take a function that is provided the match... – Heretic Monkey Aug 31 '21 at 17:04
  • Does this answer your question? [JavaScript regex - How to wrap matches with tag?](https://stackoverflow.com/questions/29616937/javascript-regex-how-to-wrap-matches-with-tag) – Heretic Monkey Aug 31 '21 at 17:12
  • 1
    Or, since you changed your question in comments to the answer, [Javascript Replace - Dynamic Value of Replacement](https://stackoverflow.com/q/57479381/215552) – Heretic Monkey Aug 31 '21 at 17:14

3 Answers3

3

You can use string#replace to change the captured group.

const string = 'Lorem ipsum dolor sit {icon_exit} consectetur {icon_plus} elit.';
const newString = string.replace(/{(.*?)}/g, (_, match) => `<i class="${match.replace('_', '-')}"></i>`);
console.log(newString);
Hassan Imam
  • 21,956
  • 5
  • 41
  • 51
1

You can use replaceAll with a regex to match against those strings and return a new string.

const string = 'Lorem ipsum dolor sit {icon_exit} consectetur {icon_plus} elit.';

const regex = /{icon_(.+?)}/g;

const replaced = string.replaceAll(regex, (match, $1) => {
  return `<i class="icon-${$1}"></i>`;
});

console.log(replaced);
Andy
  • 61,948
  • 13
  • 68
  • 95
0

Keep it simple:

function replaceWithTag(string) {
  return string
    .replace(/{icon_exit}/g, '<i class="icon-exit"></i>')
    .replace(/{icon_plus}/g, '<i class="icon-plus"></i>');
}

const string = 'Lorem ipsum dolor sit {icon_exit} consectetur {icon_plus} elit.';
console.log(replaceWithTag(string));
V P
  • 318
  • 2
  • 5
  • I guess icon_exit and icon_plus are just examples. And the replacing process should be dynamic – CyberEternal Aug 31 '21 at 17:18
  • Thanks for your answer, but this won't work, because text can have one, two or three variables. I have marked the correct answer. – Berisko Aug 31 '21 at 17:19