Home > Software engineering >  How can i bold the word before colon only if colon exists in line by regular expression
How can i bold the word before colon only if colon exists in line by regular expression

Time:12-04

These four lines are store as an array of objects in ptr

["NF: (Chuckling)","EM: And we taught not very long. Ms. Fox (ph) took my place. I met Ethan and we","were married in February (Chuckling). I had taught from September to February--","NF: Wow!"]

I am trying to show these in jsx line by line and to bold every word before colon if in some line there is no colon then it should not bold the whole line as showing below, it only bolds word before colon if there is colon in line

NF: (Chuckling)

EM: And we taught not very long. Ms. Fox (ph) took my place. I met Ethan and we

were married in February (Chuckling). I had taught from September to February--

NF: Wow!

<p key={k}>{ptr.split(/(?=:)/).map((x,i)=> i===0 ? <b key={i}>{x}</b> : x) } </p>)

CodePudding user response:

You need to check if the array you are processing inside .map() contains more than one element (to check if split actually occurred and the string was split into at least two chunks).

Add the third argument to .map() and add the && arr.length>1 check:

<p key={k}>{ptr.split(/(?=:)/).map((x,i,arr)=> i===0 && arr.length>1 ? <b key={i}>{x}</b> : x) } </p>)
  • Related