kyun
kyun

Reputation: 10264

Replace a string to JSX Tag

I have a string like it

let str = "You would get items\nwhich value about **$50**\nif you **pre-booked** it!"

I would like to replace \n to<br/> and I achieved it with the below code.

str.split('\n').map((line)=>(<span>{line}<br/></span>)

What I achieved

<span>You would get items<br/></span>
<span>which value about $50<br/></span>
<span>if you pre-booked it!</span>

And now, I want to emphasize some words like this.

What I expect

<span>You would get items<br/></span>
<span>which value about <b>$50</b><span>
<span>if you <b>pre-booked</b> it!</span>

I want to use like the below it.

const TextFormat = ({text}) => (
  <React.Fragment>
    {
      text.split('\n').map((line, i) => (<span key={i}>{line}<br/></span>)
    }
  </React.Fragment>
)

Upvotes: 3

Views: 2442

Answers (2)

Aziz.G
Aziz.G

Reputation: 3721

let str = "You would get items\nwhich value about **$50**\nif you **pre-booked** it!"

const res = str.split('\n').map(line =>

  `<span>  ${line.replace(/\*\*(.*?).\*\*/,match => `<b>${match.substring(2, match.length - 2 )}</b>`)} <br/> </span>`
)

console.log(res)

Upvotes: 1

p.s.w.g
p.s.w.g

Reputation: 149020

Within your first map, you can split the line by those specific keyword. When you include a capturing group in the regex to split, the captured substring will be included in the result array, so you can do something like this:

<React.Fragment>
  {
    str.split('\n').map(line => (
      <span>
        {line.split(/\*\*(.+?)\*\*/).map((s, i) => i % 2 ? (<b>{s}</b>) : s)}
        <br/>
      </span>
    ))
  }
</React.Fragment>

This looks like markdown. You should also consider using a markdown plugin like react-markdown to make potentially your life easier.

Upvotes: 3

Related Questions