JavaScript: How to replace particular patterns of text with HTML tags?

There is a plain text field in the CMS of an old site. Now we have to do some more complex CSS styling to change the layout.

My idea is to replace some particular patterns of text with HTML tags.

For example, to change:

<div class="wrap">
  <span>###2022-10-01###Opening Ceremony</span>
  <span>###2022-10-02###Welcoming Speech</span>
  <span>###2022-10-03###Race Day</span>
</div>

into:

<div class="wrap">
  <span><span class="date">2022-10-01</span>Opening Ceremony</span>
  <span><span class="date">2022-10-02</span>Welcoming Speech</span>
  <span><span class="date">2022-10-03</span>Race Day</span>
</div>

So, I am trying this:

let htmlContent = document.querySelector(".wrap").innerHTML;
htmlContent = htmlContent.replace(
  /###(.*?)###/g,
  '<span class="date">$1</span>'
);

It is not working. Obviously, I am missing or mistaken something. I would be so great if anyone could help! :pray:t2:

On CodePen: https://codepen.io/pen/qBYXxbm

you are modifying the wrong variable
let wrap = document.querySelector(“.wrap”);
wrap.innerHTML = wrap.innerHTML.replace(
/###(.*?)###/g,
‘$1’
);

1 Like