drkskwlkr icon

Parse HTML tables with JS

drkskwlkr | PRO | 06/17/23 08:09:28 PM UTC | 0 ⭐ | 1456 👁️ | Never ⏰ | []
JavaScript |

840 B

|

Source Code

|

0 👍

/

0 👎

const tableText = `
  <table>
    <thead>
      <tr>
        <th>Name</th>
        <th>Age</th>
        <th>City</th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td>John</td>
        <td>30</td>
        <td>New York</td>
      </tr>
      <tr>
        <td>Jane</td>
        <td>25</td>
        <td>Los Angeles</td>
      </tr>
      <tr>
        <td>Bob</td>
        <td>40</td>
        <td>Chicago</td>
      </tr>
    </tbody>
  </table>
`;
 
// Extract the row data from the table text using regular expressions
const rowData = tableText.match(/<tr>(.*?)<\/tr>/gs).map(tr => {
  const cellData = tr.match(/<td>(.*?)<\/td>/gs).map(td => td.replace(/<\/?td>/g, ''));
  return { Name: cellData[0], Age: cellData[1], City: cellData[2] };
});
 
// Log the resulting JSON object
console.log(JSON.stringify(rowData));

Comments