smuhero smuhero - 1 year ago 43
HTML Question

How to extract all td's text content from an element in the array?

How to extract td's text content and store each one into an array from another array that contain the following contents:

//create two element in the array, that store a string containing html code

tablecontentArray[0] = "`<tbody><tr><th>Title 1</th><th>Title 2</th></tr><tr><td>Fruit 1</td><td>Fruit 2</td></tr><tr><th>Title 3</th><th>Title 4</th></tr><tr><td>Fruit 3</td><td>Fruit 4</td></tr></tbody>`"

tablecontentArray[1] = "`<tbody><tr><th>Title 5</th><th>Title 6</th></tr><tr><td>Fruit 5</td><td>Fruit 6</td></tr><tr><th>Title 7</th><th>Title 8</th></tr><tr><td>Fruit 7</td><td>Fruit 8</td></tr></tbody>`"

//loop to extract the td text content from the each element of the tableContentArray and store it into extractedTdArray

extractedTdArray = [];

Answer Source

var str = "`<tbody><tr><th>Title 1</th><th>Title 2</th></tr><tr><td>Fruit 1</td><td>Fruit 2</td></tr><tr><th>Title 3</th><th>Title 4</th></tr><tr><td>Fruit 3</td><td>Fruit 4</td></tr></tbody>`"
var extractedTdArray = str.split("<td>")
  .filter(function(v){ return v.indexOf('</td>') > -1})
  .map( function(value) { 
    return value.split("</td>")[0]
  })
  console.log(extractedTdArray)

First you split up the string into arrays by <td> you get

0:"`<tbody><tr><th>Title 1</th><th>Title 2</th></tr><tr>"
1:"Fruit 1</td>"
2:"Fruit 2</td></tr><tr><th>Title 3</th><th>Title 4</th></tr><tr>"
3:"Fruit 3</td>"
4:"Fruit 4</td></tr></tbody>`"

Then you get the elements that have the closing </td> in with the filter

0:"Fruit 1</td>"
1:"Fruit 2</td></tr><tr><th>Title 3</th><th>Title 4</th></tr><tr>"
2:"Fruit 3</td>"
3:"Fruit 4</td></tr></tbody>`"

then you split it by the </td> and get the first element. we already split by <td> so we know that from the beginning is the info we want to the </td>.

["Fruit 1", "Fruit 2", "Fruit 3", "Fruit 4"]

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download