Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to parse CSV data embedded in an HTML page?

Tags:

javascript

dom

I have a HTML page full of data separated by commas and each row ends in a <br /> tag. In JavaScript I can get this from the DOM by asking for the innerHTML of the element containing the data.

My question is how to parse the innerHTML to get the data out from between the commas and start on the next line when it hits the <br /> tag?

You can probably ignore the rest as that is my question above.

When I parse each line I will start a new object and put the data into it. I'm just not sure what to do with the innerHTML!

I did put the data through a CSVtoarray function I found but ended up with an array of one large array instead of an array of arrays for each line. I can work my way through this array creating objects from the data along the way but turning the innerHTML into a single array seems an unnecessary step when I could parse the data straight into object.

The data is put there via AJAX. I can change the format that the data comes in. As I said I have it separating data with commas and <br /> tag at the end of the line. I do not know if this is stupid or not.

like image 208
Peter Bushnell Avatar asked Jan 30 '26 20:01

Peter Bushnell


1 Answers

So, you want to csv-parse a file where newlines are indicated with <br /> instead of \n? Just use that separator in your CSV-Parser then. Simple version:

text.split("<br />".map(function(line){ return line.split(","); })

You could also split by regular expressions, like

text.split(/\s*<br ?\/>\s*/)...

If you really habe the CSV data in a DOM, you could remove all the br-element and use the remaining (text) nodes as the lines-array.

like image 171
Bergi Avatar answered Feb 02 '26 10:02

Bergi