Home > Net >  How to replace particular patterns of text with HTML tags on front-end using JavaScript?
How to replace particular patterns of text with HTML tags on front-end using JavaScript?

Time:09-22

There is a field in the CMS that does not allow HTML, but now we have to do some 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 >
  <figcaption>###2022-10-01###Opening Ceremony</figcaption>
  ...
  <figcaption>###2022-10-02###Welcoming Speech</figcaption>
  ...
  <figcaption>###2022-10-03###Race Day</figcaption>
</div>

into:

<div >
  <figcaption><span >2022-10-01</span>Opening Ceremony</figcaption>
  ...
  <figcaption><span >2022-10-02</span>Welcoming Speech</figcaption>
  ...
  <figcaption><span >2022-10-03</span>Race Day</figcaption>
</div>

Note: ###2022-10-02###Welcoming Speech is what I can put into the field.
So it is not a must to be ###. It can be other text, symbols, or patterns.

Shall we use htmlContent.replace? And I have to target all matched patterns on the web page. I am not sure how to do it correctly.

  • Related