Hay un campo en el CMS que no permite HTML, pero ahora tenemos que hacer un estilo CSS complejo para cambiar el diseño.
Mi idea es reemplazar algunos patrones particulares de texto con etiquetas HTML.
Por ejemplo, para cambiar:
<div class="wrap">
<figcaption>###2022-10-01###Opening Ceremony</figcaption>
...
<figcaption>###2022-10-02###Welcoming Speech</figcaption>
...
<figcaption>###2022-10-03###Race Day</figcaption>
</div>
dentro:
<div class="wrap">
<figcaption><span class="date">2022-10-01</span>Opening Ceremony</figcaption>
...
<figcaption><span class="date">2022-10-02</span>Welcoming Speech</figcaption>
...
<figcaption><span class="date">2022-10-03</span>Race Day</figcaption>
</div>
Nota: ###2022-10-02###Welcoming Speech es lo que puedo poner en el campo.
Por lo tanto, no es obligatorio ser ### . Puede ser otro texto, símbolos o patrones.
¿ htmlContent.replace ? Y tengo que apuntar a todos los patrones coincidentes en la página web. No estoy seguro de cómo hacerlo correctamente. 🙏🏻
Probando CodePen: https://codepen.io/pen/qBYXxbm
Use un reemplazo de expresión regular.
htmlContent = htmlContent.replace(/###(.*?)###/g, '<span class="date">$1</span>');
(.*?) es un grupo de captura que captura todo entre el par de ### y $1 en las copias de cadena de reemplazo que capturó.
let htmlContent = `<figcaption>###2022-10-01###Opening Ceremony</figcaption>
...
<figcaption>###2022-10-02###Welcoming Speech</figcaption>
...
<figcaption>###2022-10-03###Race Day</figcaption>`;
htmlContent = htmlContent.replace(/###(.*?)###/g, '<span class="date">$1</span>');
console.log(htmlContent);
Los detalles se comentan en el ejemplo.
// Collect all <figcaption> into a NodeList
document.querySelectorAll("figcaption")
// For each <figcaption>...
.forEach(cap => {
// ...split it's text at "###" into an array
const text = cap.textContent.split('###')
// ...filter any empty parts of the array
.filter(t => t);
//console.log(text);
/*
Render the template literal within the <figcaption>
interpolate the content of array text
*/
cap.innerHTML = `<span class="date">${text[0]}</span> ${text[1]}`;
});
section,
figure {
display: flex;
flex-flow: column nowrap;
justify-content: center;
align-items: center;
}
.date {
color: red
}
<section>
<figure>
<img src="https://s.abcnews.com/images/International/olympics-fireworks4-gty-ml-220204_1643987789890_hpEmbed_3x2_992.jpg" width="240">
<figcaption>###2022-10-01###Opening Ceremony</figcaption>
</figure>
<figure>
<img src="https://gupshups.org/wp-content/uploads/2019/11/Welcome-speech-for-the-seminar.jpg" width="240">
<figcaption>###2022-10-02###Welcoming Speech</figcaption>
</figure>
<figure>
<img src="https://cdn.quotesgram.com/img/70/24/616754473-2c33e6276057e5c799641af64e446ccb.jpg" width="240">
<figcaption>###2022-10-03###Race Day</figcaption>
</figure>
</section>