'How to wrap a part of text fetched from array of object in a span tag?
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?
Solution 1:[1]
This should do your work!
data[0].text.replace("dolor sit amet", "<span>dolor sit amet</span>");
Solution 2:[2]
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
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Ajeet Chauhan |
| Solution 2 | Ji aSH |
