Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

123
Views
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.
about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

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

about 4 years ago · Juan Pablo Isaza Report

0

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

about 4 years ago · Juan Pablo Isaza Report

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));
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!