Advertisement
drkskwlkr

Parse HTML tables with JS

Jun 17th, 2023
1,011
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
JavaScript 0.84 KB | Source Code | 0 0
  1. const tableText = `
  2.   <table>
  3.     <thead>
  4.       <tr>
  5.         <th>Name</th>
  6.         <th>Age</th>
  7.         <th>City</th>
  8.       </tr>
  9.     </thead>
  10.     <tbody>
  11.       <tr>
  12.         <td>John</td>
  13.         <td>30</td>
  14.         <td>New York</td>
  15.       </tr>
  16.       <tr>
  17.         <td>Jane</td>
  18.         <td>25</td>
  19.         <td>Los Angeles</td>
  20.       </tr>
  21.       <tr>
  22.         <td>Bob</td>
  23.         <td>40</td>
  24.         <td>Chicago</td>
  25.       </tr>
  26.     </tbody>
  27.   </table>
  28. `;
  29.  
  30. // Extract the row data from the table text using regular expressions
  31. const rowData = tableText.match(/<tr>(.*?)<\/tr>/gs).map(tr => {
  32.   const cellData = tr.match(/<td>(.*?)<\/td>/gs).map(td => td.replace(/<\/?td>/g, ''));
  33.   return { Name: cellData[0], Age: cellData[1], City: cellData[2] };
  34. });
  35.  
  36. // Log the resulting JSON object
  37. console.log(JSON.stringify(rowData));
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement