3

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>
)

kyun
  • 9,710
  • 9
  • 31
  • 66

2 Answers2

3

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.

p.s.w.g
  • 146,324
  • 30
  • 291
  • 331
1

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)
Aziz.G
  • 3,599
  • 2
  • 17
  • 35
  • Thank you, but I am sorry. I want `jsx`, not `string` – kyun Mar 27 '19 at 21:06
  • for jsx just replace ${} with {} and remove quotes – Aziz.G Mar 27 '19 at 21:10
  • it is too close... but I can get a `string` like `something` – kyun Mar 27 '19 at 21:16
  • 1
    Just some friendly feed back: your regex pattern is a very odd. `[**]` is the same as `[*]` and `.*.` is the same as `.+`. In other words, your pattern matches a `*` followed by any number of characters and another `*` (e.g. `*foo* bar *baz*` becomes ` foo bar baz`). Also, I'd recommend using a capturing group to include only the parts you care about inside the result rather than making a second pass through to remove the `*` characters. – p.s.w.g Mar 27 '19 at 21:26