Home > Software engineering >  react-native - get text inside all <b> tags in a html string
react-native - get text inside all <b> tags in a html string

Time:11-07

Let's say i have a html string in react native. Since theres no document in react-native, im a bit confused on how this can be achieved

const htmlString = '<div style="margin-left: 10px">I have three dogs. One is called <b>Tiger</b>, the second is called <b>Lion</b>, and the third is called <b>Panda</b>.</div>'

I want to extract the text inside each <b> tag. There can be more than 10 <b> tags in this html string. The <b> tag can also be nested on many levels within the string

Expected output:

Tiger
Lion
Panda

This data can be stored in array or as object. Please note: This is in react-native

Thank you

I tried something like

htmlString.split('<b>').pop().split('</b>')[0]

that returns only Panda. cannot find a way to get the previous ones too

CodePudding user response:

You can try this:

const reg = /<b>(.*?)<\/b>/g
for (const match of htmlString.matchAll(reg)) {
  console.log(`matched: ${match[1]}`);
}

Result:

matched: Tiger
matched: Lion
matched: Panda

CodePudding user response:

He @duttasuraj you can try this => htmlString.split(<b>)[1].split(</b>)[0]

  • Related