Home > Blockchain >  Converting text with <strong></strong> tags into actual bold text?
Converting text with <strong></strong> tags into actual bold text?

Time:09-30

I have some incoming text from the backend that contains tags within the text to indicate bold. Since it's dynamic text, I need to catch any instance of a tag and convert to actual bold rendering. I assume regex is the answer but not sure of the configuration. It needs to apply bold and strip out the tags.

This is a message that has a phone number that needs to be bold. Please call: <strong>888-888-8888</strong>

The context is a react native app.

CodePudding user response:

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>

If its in the context of a react app then its even simpler. You would just do something like this.

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>)/);

Then in the JSX section something like this:

<div>{textSegments.map(segment => {
if (segment.includes('strong')) {
const text = segment.replace('<strong>','').replace('</strong>', '');
return <strong>{text}</strong>;
} else {
return segment;
}
})}</div>

Something like this should work.

CodePudding user response:

If you want to replace a tag with a strong tag you can do this:

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>');

CodePudding user response:

I think you can go ahead with the text which contains tag

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>

  • Related