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

104
Views
Add new tag to the middle of element

I am trying to surround specific words in textContent with HTML tags, this could hypothetically be done by doing element.textContent = element.textContent.replaceAll("word", "<h1>word<h1>"); but that isn't parsed, and element.innerHTML= element.innerHTML.replaceAll("word", "<h1>word<h1>"); doesn't work because there is a risk that the word could be the name of a tag. Is there any solution besides writing a custom replace function that detects when in a tag?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

You can make sure that the word you're trying to pad is not inside a tag. To do this, you need to check its surrounding characters. As long as they aren't enclosed by < and > on both sides (or make sure they are enclosed by <some tag> on the left and </?some tag> on the right like what I did below), they should be the only one to be replaced. Try this regex sample below:

function padTags(content, openTag, word, closeTag) {
  console.log(content)
  const replacement = openTag + word + closeTag;
  const regex = `(?<!<[^<>]*)${word}(?![^<>]*>)`;
  const pattern = new RegExp(regex, 'g');
  return content.replace(pattern, replacement);
}

console.log(padTags(`<p class="questions">What's your favorite class?</p>`, 
                '<custom-tag>', 'class', '</custom-tag>'));
console.log(padTags(`<div><p class="test">class</p></div>`,
                '<custom-tag>', 'class', '</custom-tag>'));
console.log(padTags(`<div> class <p data-customvar="<class>">This is my class </p>class</div>`,
                '<custom-tag>', 'class', '</custom-tag>'));

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!