简体   繁体   中英

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 = [];

setting one table and push

var extractedTdArray = [];// create result array

// loop across html strings
$.each(tablecontentArray, function (key, table) {
    $('#table').html(table);//create html table
        // loop across the created table td's
        $.each($('#table').find('td'), function (key2, td) {
            var tdVal=$(this).text();// td value
            //push to array
            extractedTdArray.push(tdVal);
        });
    });
});

setting multiple tables and map

// set tables
$.each(tablecontentArray, function (key, table) {
    $('#table' + key).html(table).addClass('table');
});

// map td
var extractedTdArray = $('.table tr:has(td)').map(function (i, v) {
    return $(this).text();
}).get();

 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"]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM