Given a json object as below:
const data = [
{
id: "text1",
text: "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam sollicitudin odio a luctus ornare. Pellentesque nisl tis tellus nec, dapibus turpis. In hac habitasse platea vitae.",
},
];
If I want to include part of text fetched inside a <span>
tag such as:
<p>Lorem ipsum <span>dolor sit amet</span>. </p>
How do I do this?
CodePudding user response:
Based on your comment, I imagine that you know which text should be put under the span
const data = [
{
id: "text1",
text: "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam sollicitudin odio a luctus ornare. Pellentesque nisl tis tellus nec, dapibus turpis. In hac habitasse platea vitae.",
},
];
const textToSpan = 'dolor sit amet';
In this case you can split your string and render with something like this:
const aText = data.text.split(textToSpan);
const aTextRender = aText.reduce((result, t) => {
if (result.length) {
result.push(<span>{textToSpan}<span>);
}
result.push(t);
return result;
}, [])
return (
<p>
{aTextRender}
<p>
);
Code not tested though :o
CodePudding user response:
This should do your work!
data[0].text.replace("dolor sit amet", "<span>dolor sit amet</span>");