Berisko
Berisko

Reputation: 643

Javascript dynamicaly replace regex matches

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.

Upvotes: 1

Views: 55

Answers (3)

V P
V P

Reputation: 348

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

Upvotes: 0

Andy
Andy

Reputation: 63524

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

Upvotes: 1

Hassan Imam
Hassan Imam

Reputation: 22524

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

Upvotes: 3

Related Questions