Tengo un texto entrante del backend que contiene etiquetas dentro del texto para indicar negrita. Dado que es texto dinámico, necesito capturar cualquier instancia de una etiqueta y convertirla a una representación en negrita real. Supongo que regex es la respuesta, pero no estoy seguro de la configuración. Necesita aplicar negrita y quitar las etiquetas.
This is a message that has a phone number that needs to be bold. Please call: <strong>888-888-8888</strong>El contexto es una aplicación nativa de reacción.
const text = "This is a message that has a phone number that needs to be bold. Please call: <strong>888-888-8888</strong>.Here is another phone number <strong>888-888-8888</strong>"; const textDiv = document.getElementById('text'); const textSegments = text.split(/(<strong>.*?<\/strong>)/); textSegments.forEach(textSegment => { if (textSegment.includes('strong')) { const span = document.createElement('strong'); span.appendChild(document.createTextNode(textSegment.replace('<strong>','').replace('</strong>', ''))); textDiv.appendChild(span); } else { const text = document.createTextNode(textSegment); textDiv.appendChild(text); } }) <div id="text"></div>Si está en el contexto de una aplicación de reacción, entonces es aún más simple. Simplemente harías algo como esto.
const text = "This is a message that has a phone number that needs to be bold. Please call: <strong>888-888-8888</strong>.Here is another phone number <strong>888-888-8888</strong>"; const textSegments = text.split(/(<strong>.*?<\/strong>)/);Luego, en la sección JSX algo como esto:
<div>{textSegments.map(segment => { if (segment.includes('strong')) { const text = segment.replace('<strong>','').replace('</strong>', ''); return <strong>{text}</strong>; } else { return segment; } })}</div>Algo como esto debería funcionar.
Si desea reemplazar una etiqueta con una etiqueta fuerte, puede hacer esto:
var text = 'This <div>is a message that has a phone number that needs to be bold</div>. Please call: <strong>888-888-8888</strong>' text.replace('div>', 'strong>');Creo que puedes continuar con el texto que contiene la etiqueta.
document.getElementById("dynamictext").innerHTML = "This is a message that has a phone number that needs to be bold. Please call: <strong>888-888-8888</strong>"; <div id="dynamictext"></div>