简体   繁体   中英

How to replace/inject html tags in a text in node?

I have a component in react js project which displays some text. the text variable is of type string and has some tab escape charcters within. I would like to replace this tab character and use a div. how do i replace this with a such that when it renders, it outputs the div within the when it renders HTML. so on the page source in browser i see something like this => <span> once upon a time, <div> there was a man <div> who had a house. </span> <span> once upon a time, <div> there was a man <div> who had a house. </span>

text = "once upon a time, \t there was a man \t who had a house.";

class somcomponent extends React.Component {
  render() {
    return <span> {text}</span>;
  }
}

You can split your text by \t and render a div each split, like this:

class somcomponent extends React.Component {
  render() {
    return <span>
      {text.split('\t').map(s=><div>{s}</div>)}
    </span>
  }
}

In a snippet:

 const rootElement = document.getElementById("root"); ReactDOM.render( <Demo />, rootElement ); function Demo() { let text = "once upon a time, \t there was a man \t who had a house."; return ( <span> {text.split('\t').map(s=><div>{s}</div>)} </span> ); }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script> <div id="root"></div>

text.split('\t') will split your text into a list of strings that are between '\t'.

Now, use map to render <div>{s}</div> for each element in that list, while s is current string you're iterating.

Hi Ozil,

Go ahead and give this snippet a try to see if this is what you are trying to achieve, pal! let us know the outcome on your end!

 const domEl = document.getElementById("container"); ReactDOM.render(<RemoveTabs />,domEl); function RemoveTabs() { let text ="Once upon a time, \t there was a man \t who had a house."; return(<div>{"<div>"+text.replace(/\t/g,'</div><div>')+"<div>"}</div>); }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.4.2/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.4.2/umd/react-dom.production.min.js"></script> <div id="container"></div>

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