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.
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);
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);
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));