How to Convert HTML to CSV Using JavaScript?

Estimated read time 2 min read

To convert HTML to CSV using JavaScript, you can parse the HTML content and extract the data you need, and then format the data as CSV using a library or by writing your own code.

Here’s a simple example that uses a JavaScript regular expression to extract data from an HTML table and format it as CSV:

function htmlToCsv(html) {
  let rows = html.match(/<tr>(.*?)<\/tr>/g);
  let csv = '';
  if (rows) {
    rows.forEach(row => {
      let cells = row.match(/<td>(.*?)<\/td>/g);
      if (cells) {
        let csvRow = cells.map(cell => cell.replace(/<td>|<\/td>/g, '')).join(',');
        csv += csvRow + '\n';
      }
    });
  }
  return csv;
}

In the example, the htmlToCsv function takes a string of HTML as its input and returns a string of CSV data. The match method is used to extract the rows of the HTML table using a regular expression, and then for each row, the cells are extracted and formatted as a CSV row using another regular expression and the map and join methods.

Note that this is just a simple example, and depending on the structure and complexity of your HTML content, you may need to modify the regular expressions or use a different approach to parse the data. Additionally, you may also want to consider using a library or package that provides more robust and flexible HTML parsing and CSV generation capabilities.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply