简体   繁体   中英

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?

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

This should do your work!

    data[0].text.replace("dolor sit amet", "<span>dolor sit amet</span>");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM